题目如下:
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.
- You must use only standard operations of a queue -- which means only
push to back
,peek/pop from front
,size
, andis 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的时候做一些手脚,每次有新元素offer进来的时候,我们就把它之前的元素通过offer(poll)操作放到队列后面去,这样就变相将最新的元素一直保持在队列的首部。这样,我们在进行pop和top操作的时候就可以直接调用linkedList中的poll和peek实现这些功能。老规矩,已Accepted的代码如下:
class MyStack {
private LinkedList<Integer> stack;
public MyStack(){
stack = new LinkedList<Integer>();
}
// Push element x onto stack.
public void push(int x) {
stack.offer(x);
for(int i=0;i<stack.size()-1;i++){
stack.offer(stack.poll());
}
}
// Removes the element on top of the stack.
public void pop() {
stack.poll();
}
// Get the top element.
public int top() {
if(stack.isEmpty()){
return -1;
}else{
return stack.peek();
}
}
// Return whether the stack is empty.
public boolean empty() {
return stack.isEmpty();
}
}
这道题是有Editorial Solution的,地址在这里:https://leetcode.com/articles/implement-stack-using-queues/ 。里面有图有真相,大家自己去看就能看懂。