当前位置:首页 » 编程语言

leetcode_Implement Stack using Queues

2015-08-07 09:49 本站整理 浏览(140)

描述:

Implement the following operations of a stack using queues.

push(x) -- Push element x onto stack.

pop() -- Removes the element on top of the stack.

top() -- Get the top element.

empty() -- Return whether the stack is empty.

Notes:

You must use only standard operations of a queue -- which means only push to back, peek/pop from front, size, and is empty operations are valid.

Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.

You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

思路:

1.跟用栈实现队列不同,我感觉用队列去实现栈要困难的多,以至于根本就想不起来,参考了网络上的思路才算是有了写头绪,原来是这个这个样子。。。

2.如果用栈来实现队列还算可以理解的话,但用队列来实现栈就只有两个字来形容:no zuo no die!,下面我就来描述下这种奇葩的思路:

3.用两个队列queue1和queue2来模拟栈,具体怎么模拟呢?queue1是操作队列,先进先出,queue2是中转队列,每次取元素时,将0~size-2个元素先中转到queue2中,然后取出queue1的最后一个元素,然后,对,然后在将queue1中的元素再依次放回queue2中,直至stack2为空且没有新的元素进栈,循环终止

4.好有想法的一个思路,希望还有更简洁明快的思路出现。

代码:

class MyStack {
    Deque<Integer>queue1=new LinkedList<Integer>();
	Deque<Integer>queue2=new LinkedList<Integer>();
	// Push element x onto stack.
	public void push(int x)
	{
		queue1.addLast(x);;
	}

	// Removes the element on top of the stack.
	public void pop()
	{
		if(!this.empty())
		{
			int size=queue1.size()-1;
			for(int i=0;i<size;i++)
				queue2.addLast(queue1.pop());
			queue1.pop();
		}
		queue1.addAll(queue2);
		queue2.clear();
	}

	// Get the top element.
	public int top()
	{
		int num=0;
		if(!this.empty())
		{
			int size=queue1.size()-1;
			for(int i=0;i<size;i++)
				queue2.addLast(queue1.pop());
			num=queue1.pop();
			queue1.addAll(queue2);
			queue1.addLast(num);
			queue2.clear();
		}
		return num;
	}

	// Return whether the stack is empty.
	public boolean empty()
	{
		if(queue1.size()==0)
			return true;
		return false;
	}
}