Vulkan

Cracking The Coding Interview 3.5

//Implement a MyQueue class which implements a queue using two stacks.
#include <iostream>
#include<stack>
using namespace std;
class MyQueue
{
public:
	stack<int> data,buffer;

	MyQueue()
	{
	}

	void EnQueue(int e)
	{
		data.push(e);
	}

	int DeQueue()
	{
		if (data.empty())
		{
			return -1;
		}

		while(!data.empty())
		{
			buffer.push(data.top()) ;
			data.pop();
			
		}
		int t = buffer.top();
		buffer.pop();

		while(!buffer.empty())
		{
			data.push(buffer.top());
			buffer.pop();
		}
		return t;
	}


};

int main()
{
	MyQueue s;

	for (int i =0; i<10; i++)
	{
		s.EnQueue(i);
	}
	cout<<endl;

	for (int i=0; i<10;i++)
	{
		cout<<s.DeQueue();
	}
	
	return 0;
}

posted on 2014-04-11 09:54  Vulkan  阅读(184)  评论(0编辑  收藏  举报

导航