面試題:用兩個棧實現(xiàn)隊列,用兩個隊列實現(xiàn)棧

兩個棧實現(xiàn)一個隊列:

目前創(chuàng)新互聯(lián)公司已為近1000家的企業(yè)提供了網(wǎng)站建設、域名、網(wǎng)站空間網(wǎng)站托管、企業(yè)網(wǎng)站設計、滄州網(wǎng)站維護等服務,公司將堅持客戶導向、應用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長,共同發(fā)展。

template<class T>
class CQueue
{
public:
	void Push(const T& element)
	{
		stack1.push(element);
	}

	void Pop()
	{
		if (stack2.empty())
		{
			while (!stack1.empty())
			{
				stack2.push(stack1.top());
				stack1.pop();
			}
		}

		if (stack2.empty())
		{
			cout<<"queue is empty"<<endl;
			assert(false);
		}

		stack2.pop();
	}

	bool Empty()
	{
		if (stack1.empty() && stack2.empty())
			return true;
		else
			return false;

	}

	T Front()
	{
		if (!stack2.empty())
		{
			return stack2.top();
		}
		else
		{
			while (!stack1.empty())
			{
				stack2.push(stack1.top());
				stack1.pop();
			}

			if (stack2.empty())
			{
				cout<<"queue is empty"<<endl;
				assert(false);
			}

			return stack2.top();
		}
	}

private:
	stack<T> stack1;
	stack<T> stack2;
};

兩個隊列實現(xiàn)一個棧:

template<class T>
class CStack
{
public:
	void Push(const T& element)
	{
		queue1.push(element);
	}

	void Pop()
	{
		if (queue1.empty())
		{
			cout<<"stack is empty"<<endl;
			assert(false);
		}

		while (queue1.size() != 1)
		{
			queue2.push(queue1.front());
			queue1.pop();
		}

		queue1.pop();

		while (!queue2.empty())
		{
			queue1.push(queue2.front());
			queue2.pop();
		}
	}

	bool Empty()
	{
		if (queue1.empty())
			return true;
		else
			return false;
	}

	T Top()
	{
		if (queue1.empty())
		{
			cout<<"stack is empty"<<endl;
			assert(false);
		}
		return queue1.back();
	}

private:
	queue<T> queue1;
	queue<T> queue2;
};

網(wǎng)站名稱:面試題:用兩個棧實現(xiàn)隊列,用兩個隊列實現(xiàn)棧
本文URL:http://bm7419.com/article30/gihjpo.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供域名注冊、全網(wǎng)營銷推廣微信小程序、網(wǎng)頁設計公司網(wǎng)站改版、網(wǎng)站設計公司

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設計