您的位置:首页 > 产品设计 > UI/UE

Leetcode225. Implement Stack using Queues

2016-12-12 16:41 344 查看
该题和232题类似,思想上差不多232题

原题

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).

翻译

使用队列实现堆栈的以下操作。

push(x) - 将元素x推入堆栈。

pop() - 删除堆栈顶部的元素。

top() - 获取顶层元素。

empty() - 返回堆栈是否为空。

您必须只使用队列的标准操作 - 这意味着从前面看/弹出,大小和空操作都有效。

根据您的语言,队列可能不支持本机。 您可以使用列表或deque(双端队列)模拟队列,只要只使用队列的标准操作即可。

您可以假定所有操作都是有效的(例如,不会在空堆栈上调用pop或top操作)。

思路

使用两个队列来完成一个栈,把队列的元素移到另一个队列,直到还剩最后一个;这个元素即为栈顶的元素。

代码

class MyStack {
private Queue<Integer>queue1=new LinkedList<>();
private Queue<Integer>queue2=new LinkedList<>();
// Push element x onto stack.添加元素至栈中
public void push(int x) {
queue1.offer(x);

}

// Removes the element on top of the stack.从栈顶移除元素
public void pop() {
if (queue1.size()==0) {
return;

}
//逐个把队1的元素移动到队中,直至剩一个元素,则为栈顶的元素

while(queue1.size()>1)
queue2.offer(queue1.poll());
queue1.poll();
//注意先把队2中元素复制到队1中,然后再将队2元素置为空
Queue<Integer>q=queue2;
queue2=queue1;
queue1=q;
}

// Get the top element.
//返回栈顶的元素
public int top() {
if (queue1.size()==0) {
return 0;

}
//将队1中元素移到队2中,然后剩下最后一个,就是栈顶元素
while(queue1.size()>1)
queue2.offer(queue1.poll());
int temp= queue1.poll();
//把最后一个抛出去的元素加进队列2中,然后队1和队2的元素互换
queue2.offer(temp);
Queue<Integer>q=queue2;
queue2=queue1;
queue1=q;
return temp;

}

// Return whether the stack is empty.
public boolean empty() {
return queue1.isEmpty();

}
}


[原题链接](https://leetcode.com/problems/implement-stack-using-queues/)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列-栈