Implement Stack using Two Queues

后端 未结 23 725
感情败类
感情败类 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:50

    Efficient solution in C#

    public class MyStack {
        private Queue q1 = new Queue();
        private Queue q2 = new Queue();
        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;
        }
    }
    

提交回复
热议问题