使用队列堆栈

时间:2010-10-28 01:53:13

标签: algorithm

我正在浏览一些面试问题并偶然发现了这一点。它让我撕裂了我的头发。

有谁知道如何使用队列实现堆栈?

4 个答案:

答案 0 :(得分:5)

push:将元素插入队列的后面。

pop:从前面删除一个元素,立即将其插入后面,重复N-1次,其中N是队列的大小,然后删除最后一个元素并将其返回。

答案 1 :(得分:0)

版本A:

推:

在队列1中排队

流行:

当queue1的大小大于1时,管道将队列从队列中排队到队列2中 出队并返回queue1的最后一项,然后切换queue1和queue2的名称

版本B:

推:

在队列2中排队 将queue1中queue1的所有项排入队列,然后切换queue1和queue2的名称

流行:

来自queue1的

deqeue

答案 2 :(得分:0)

使用一个队列实现堆栈的概念需要O(2n)或(机器无关)O(n)空间复杂度。但是当你正在为大尺寸阵列工作时,可能无法使用双倍大小的数据,如果你只尝试使用一个,那么时间复杂度也是O(n ^ 2)或精确为O(n *(n + 1)/ 2)队列中。

答案 3 :(得分:0)

使用队列执行堆栈的以下操作。

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

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

top()-获取顶部元素。

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

enter image description here

class MyStack {

  Queue<Integer> q;
  /** Initialize your data structure here. */

  public MyStack() {
    q = new LinkedList<Integer>();
  }

  /** Push element x onto stack. */
  public void push(int x) {
    q.offer(x);

    for(int i = 1 ; i < q.size() ; i++) {
        q.offer(q.poll());
    }
  }

  /** Removes the element on top of the stack and returns that element. */
  public int pop() {
     return q.isEmpty() ? -1 : q.poll();
  }

  /** Get the top element. */
  public int top() {
    return q.isEmpty() ? -1 : q.peek();
  }

  /** Returns whether the stack is empty. */
  public boolean empty() {
    return q.isEmpty();
  }
}
相关问题