C# O(1) O(1) solution based on StefanPochmann's approach


  • 0
    P
    public class MyStack {
        private Queue<Qu> q;
        
        /** Initialize your data structure here. */
        public MyStack() {
            this.q = new Queue<Qu>();
        }
        
        /** Push element x onto stack. */
        public void Push(int x) {
            Queue<Qu> newq = new Queue<Qu>();
            newq.Enqueue(new Qu(x));
            newq.Enqueue(new Qu(this.q));
    
            this.q = newq;
        }
        
        /** Removes the element on top of the stack and returns that element. */
        public int Pop() {
            Qu intqu = this.q.Dequeue();
            this.q = this.q.Dequeue().q;
            
            return intqu.x;
        }
        
        /** Get the top element. */
        public int Top() {
            Qu intqu = this.q.Peek();
            return intqu.x;
        }
        
        /** Returns whether the stack is empty. */
        public bool Empty() {
            return 0 == this.q.Count;
        }
        
        private class Qu{
            public Queue<Qu> q = null;
            public int x;
            
            public Qu(int argx){
                x = argx;
            }
            
            public Qu(Queue<Qu> argq){
                this.q = argq;
            }
        }
    }
    
    /**
     * Your MyStack object will be instantiated and called as such:
     * MyStack obj = new MyStack();
     * obj.Push(x);
     * int param_2 = obj.Pop();
     * int param_3 = obj.Top();
     * bool param_4 = obj.Empty();
     */
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.