Stack using queue

I looked through some interview questions and came across this. It made me tear my hair apart.

Does anyone know how to implement a stack using a queue?

+5
source share
4 answers

push: insert an item in the back of the queue.

pop: delete the element in front, insert it immediately in the back, repeat N-1 times, where N is the size of the queue, then delete the last element and return it.

+5
source

Version A:

button:

enqueue in queue1

pop:

while the size of queue1 is greater than 1, overloaded objects from queue1 to queue2 dequeue and return the last element of queue1, then switch the names queue1 and queue2

Version B:

button:

enqueue queue2 enqueue queue1 queue2, queue1 queue2

:

deqeue from queue1

0

O (2n) ( ) O (n) . , , O (n ^ 2) O (n * (n + 1)/2), .

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();
  }
}
0

All Articles