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) -- 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).
用两个队列来实现堆栈后进先出的功能。代码如下:
class MyStack {
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
// Push element x onto stack.
public void push(int x) {
q1.offer(x);
}
// Removes the element on top of the stack.
public void pop() {
while(q1.size() > 1)
q2.offer(q1.poll());
q1.poll();
Queue<Integer> tem = q1;
q1 = q2;
q2 = tem;
}
// Get the top element.
public int top() {
while(q1.size() > 1)
q2.offer(q1.poll());
int result = q1.poll();
q2.offer(result);
Queue<Integer> tem = q1;
q1 = q2;
q2 = tem;
return result;
}
// Return whether the stack is empty.
public boolean empty() {
return q1.isEmpty();
}
}
本文详细介绍了如何利用两个队列来实现栈的基本操作,包括入栈、出栈、获取栈顶元素和判断栈是否为空。通过代码示例,深入浅出地解释了这一过程。
367

被折叠的 条评论
为什么被折叠?



