Implement Stack using Two Queues

后端 未结 23 635
感情败类
感情败类 2020-11-28 17:05

A similar question was asked earlier there, but the question here is the reverse of it, using two queues as a stack. The question...

Given two queues with their sta

相关标签:
23条回答
  • 2020-11-28 17:47

    Here is my solution that works for O(1) in average case. There are two queues: in and out. See pseudocode bellow:

    PUSH(X) = in.enqueue(X)
    
    POP: X =
      if (out.isEmpty and !in.isEmpty)
        DUMP(in, out)
      return out.dequeue
    
    DUMP(A, B) =
      if (!A.isEmpty)
        x = A.dequeue()
        DUMP(A, B)
        B.enqueue(x)
    
    0 讨论(0)
  • 2020-11-28 17:48

    Here's one more solution:

    for PUSH : -Add first element in queue 1. -When adding second element and so on, Enqueue the element in queue 2 first and then copy all the element from queue 1 to queue2. -for POP just dequeue the element from the queue from you inserted the last element.

    So,

    public void push(int data){
    if (queue1.isEmpty()){
        queue1.enqueue(data);
    }  else {
    queue2.enqueue(data);
    while(!queue1.isEmpty())
    Queue2.enqueue(queue1.dequeue());
    //EXCHANGE THE NAMES OF QUEUE 1 and QUEUE2
    

    } }

    public int pop(){
    int popItem=queue2.dequeue();
    return popItem;
    }'
    

    There is one problem, I am not able to figure out, how to rename the queues???

    0 讨论(0)
  • 2020-11-28 17:48

    Below is a very simple Java solution which supports the push operation efficient.

    Algorithm -

    1. Declare two Queues q1 and q2.

    2. Push operation - Enqueue element to queue q1.

    3. Pop operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the popped element. Swap the queues q1 and q2. Return the stored popped element.

    4. Peek operation - Ensure that queue q2 is not empty. If it is empty, then dequeue all the elements from q1 except the last element and enqueue it to q2 one by one. Dequeue the last element from q1 and store it as the peeked element. Enqueue it back to queue q2 and swap the queues q1 and q2. Return the stored peeked element.

    Below is the code for above algorithm -

    class MyStack {
    
        java.util.Queue<Integer> q1;
        java.util.Queue<Integer> q2;
        int SIZE = 0;
    
        /** Initialize your data structure here. */
        public MyStack() {
            q1 = new LinkedList<Integer>();
            q2 = new LinkedList<Integer>();
    
        }
    
        /** Push element x onto stack. */
        public void push(int x) {
            q1.add(x);
            SIZE ++;
    
        }
    
        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            ensureQ2IsNotEmpty();
            int poppedEle = q1.remove();
            SIZE--;
            swapQueues();
            return poppedEle;
        }
    
        /** Get the top element. */
        public int top() {
            ensureQ2IsNotEmpty();
            int peekedEle = q1.remove();
            q2.add(peekedEle);
            swapQueues();
            return peekedEle;
        }
    
        /** Returns whether the stack is empty. */
        public boolean empty() {
            return q1.isEmpty() && q2.isEmpty();
    
        }
    
        /** move all elements from q1 to q2 except last element */
        public void ensureQ2IsNotEmpty() {
            for(int i=0; i<SIZE-1; i++) {
                q2.add(q1.remove());
            }
        }
    
        /** Swap queues q1 and q2 */
        public void swapQueues() {
            Queue<Integer> temp = q1;
            q1 = q2;
            q2 = temp;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 17:50

    Efficient solution in C#

    public class MyStack {
        private Queue<int> q1 = new Queue<int>();
        private Queue<int> q2 = new Queue<int>();
        private int count = 0;
    
        /**
         * Initialize your data structure here.
         */
        public MyStack() {
        }
    
        /**
         * Push element x onto stack.
         */
        public void Push(int x) {
            count++;
            q1.Enqueue(x);
            while (q2.Count > 0) {
                q1.Enqueue(q2.Peek());
                q2.Dequeue();
            }
            var temp = q1;
            q1 = q2;
            q2 = temp;
        }
    
        /**
         * Removes the element on top of the stack and returns that element.
         */
        public int Pop() {
            count--;
            return q2.Dequeue();
        }
    
        /**
         * Get the top element.
         */
        public int Top() {
            return q2.Peek();
        }
    
        /**
         * Returns whether the stack is empty.
         */
        public bool Empty() {
            if (count > 0) return false;
            return true;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 17:51

    Here's my answer - where the 'pop' is inefficient. Seems that all algorithms that come immediately to mind have N complexity, where N is the size of the list: whether you choose to do work on the 'pop' or do work on the 'push'

    The algorithm where lists are traded back and fourth may be better, as a size calculation is not needed, although you still need to loop and compare with empty.

    you can prove this algorithm cannot be written faster than N by noting that the information about the last element in a queue is only available through knowing the size of the queue, and that you must destroy data to get to that element, hence the 2nd queue.

    The only way to make this faster is to not to use queues in the first place.

    from data_structures import queue
    
    class stack(object):
        def __init__(self):
            q1= queue 
            q2= queue #only contains one item at most. a temp var. (bad?)
    
        def push(self, item):
            q1.enque(item) #just stick it in the first queue.
    
        #Pop is inefficient
        def pop(self):
            #'spin' the queues until q1 is ready to pop the right value. 
            for N 0 to self.size-1
                q2.enqueue(q1.dequeue)
                q1.enqueue(q2.dequeue)
            return q1.dequeue()
    
        @property
        def size(self):
            return q1.size + q2.size
    
        @property
        def isempty(self):
            if self.size > 0:
               return True
            else
               return False
    
    0 讨论(0)
  • 2020-11-28 17:51

    Here is some simple pseudo code, push is O(n), pop / peek is O(1):

    Qpush = Qinstance()
    Qpop = Qinstance()
    
    def stack.push(item):
        Qpush.add(item)
        while Qpop.peek() != null: //transfer Qpop into Qpush
            Qpush.add(Qpop.remove()) 
        swap = Qpush
        Qpush = Qpop
        Qpop = swap
    
    def stack.pop():
        return Qpop.remove()
    
    def stack.peek():
        return Qpop.peek()
    
    0 讨论(0)
提交回复
热议问题