领扣(LeetCode)用队列实现栈 个人题解

使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

注意:

  • 你只能使用队列的基本操作-- 也就是 push to backpeek/pop from frontsize, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。

具体的思路就是,在插入的时候,把队列中原有的内容依次取出再插入队列中,这样就能用队列的poll()和peek()来模拟栈的弹出。

比如: 队列中已有 1 2 3 4 5 6 7,插入 9 后并执行完操作后,变成 9 1 2 3 4 5 6 7,这时弹出队列头的次序就是 9 1 2 3 4 5 6 7,和栈一致。

代码如下:

 1 class MyStack {
 2     Queue<Integer> queue;
 3     
 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         int size=queue.size();
13         queue.add(x);
14         for(int i=0;i<size;i++)
15         {
16             Integer tmp=queue.poll();
17             queue.add(tmp);
18         }
19     }
20     
21     /** Removes the element on top of the stack and returns that element. */
22     public int pop() {
23         return queue.poll();
24     }
25     
26     /** Get the top element. */
27     public int top() {
28         return queue.peek();
29     }
30     
31     /** Returns whether the stack is empty. */
32     public boolean empty() {
33         return queue.isEmpty();
34     }
35 }
原文地址:https://www.cnblogs.com/axiangcoding/p/10091967.html