142.Implement Stack using Queues

题目:

Implement the following operations of a stack using queues.

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

  • push(x) -- Push element x onto stack.        push(x) - 将元素x推入堆栈。
  • pop() -- Removes the element on top of the stack.           pop() - 删除堆栈顶部的元素。
  • top() -- Get the top element.          top() - 获取顶部元素。
  • empty() -- Return whether the stack is empty.     empty() - 返回堆栈是否为空。

Example:

MyStack stack = new MyStack();

stack.push(1);
stack.push(2);  
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false

Notes:

  • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, 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.根据您的语言,本机可能不支持队列。 只要您只使用队列的标准操作,就可以使用list或deque(双端队列)来模拟队列。
  • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).您可以假设所有操作都是有效的(例如,在空堆栈上不会调用pop或top操作)

解答:

 1 class MyStack {
 2     
 3     private Queue<Integer> queue;
 4 
 5     /** Initialize your data structure here. */
 6     public MyStack() {
 7         queue=new LinkedList<>();
 8     }
 9     
10     /** Push element x onto stack. */
11     public void push(int x) {
12         queue.add(x);
13         for(int i=1;i<queue.size();i++)
14             queue.add(queue.poll());
15     }
16     
17     /** Removes the element on top of the stack and returns that element. */
18     public int pop() {
19         return queue.poll();
20     }
21     
22     /** Get the top element. */
23     public int top() {
24         return queue.peek();
25     }
26     
27     /** Returns whether the stack is empty. */
28     public boolean empty() {
29         return queue.isEmpty();
30     }
31 }
32 
33 /**
34  * Your MyStack object will be instantiated and called as such:
35  * MyStack obj = new MyStack();
36  * obj.push(x);
37  * int param_2 = obj.pop();
38  * int param_3 = obj.top();
39  * boolean param_4 = obj.empty();
40  */

详解:

队列:先进先出    栈:先进后出

队列push元素时:每次把新值插到最前面,这样队列的顺序和栈的顺序相反,pop的方式也相反,则正好可以实现

 

posted @ 2018-09-07 20:25  chan_ai_chao  阅读(80)  评论(0编辑  收藏  举报