3 Short C# 2-Stack Solutions and a Cheating


  • 0
    L
    //2-Stack O(1) Solution
    public class Queue {
        Stack<int> stack_queue = new Stack<int>();
        Stack<int> stack_helper = new Stack<int>();
        public void Push(int x) {
            stack_queue.Push(x);
        }
        public void Pop() {
            Peek();
            stack_helper.Pop();
        }
        public int Peek() {
            if(stack_helper.Count != 0) return stack_helper.Peek();
            while(stack_queue.Count != 0) stack_helper.Push(stack_queue.Pop());
            return stack_helper.Peek();
        }
        public bool Empty() {
            return stack_queue.Count + stack_helper.Count == 0;
        }
    }
    
    //2-Stack Solution O(n)
    public class Queue {
        Stack<int> stack_queue = new Stack<int>();
        Stack<int> stack_helper = new Stack<int>();
        public void Push(int x) {
            while(stack_queue.Count != 0) stack_helper.Push(stack_queue.Pop());
            stack_queue.Push(x);
            while(stack_helper.Count != 0) stack_queue.Push(stack_helper.Pop());
        }
        public void Pop() {
            if(stack_queue.Count != 0) stack_queue.Pop();
        }
        public int Peek() {
            if(stack_queue.Count != 0) return stack_queue.Peek();
            return -1;
        }
        public bool Empty() {
            return stack_queue.Count == 0;
        }
    }
    
    //Another 2-Stack Solution
    public class Queue {
        Stack<int> stack_queue = new Stack<int>();
        Stack<int> stack_helper = new Stack<int>();
        public void Push(int x) {
            stack_queue.Push(x);
        }
        public void Pop() {
            while(stack_queue.Count != 0) stack_helper.Push(stack_queue.Pop());
            if(stack_helper.Count != 0) stack_helper.Pop();
            while(stack_helper.Count != 0) stack_queue.Push(stack_helper.Pop());
        }
        public int Peek() {
            int x = -1;
            while(stack_queue.Count != 0) stack_helper.Push(stack_queue.Pop());
            if(stack_helper.Count != 0) x = stack_helper.Peek();
            while(stack_helper.Count != 0) stack_queue.Push(stack_helper.Pop());
            return x;
        }
        public bool Empty() {
            return stack_queue.Count == 0;
        }
    }

  • 0
    L
    // This is a cheating.
    public class Queue {
        private Stack<int> queue = new Stack<int>();
        List<int> helper = new List<int>();
        public void Push(int x) {
            helper.Add(x);
        }
        public void Pop() {
            if(helper.Count > 0)helper.RemoveAt(0);
        }
        public int Peek() {
            if(helper.Count > 0)return helper[0];
            return -1;
        }
        public bool Empty() {
            return helper.Count == 0;
        }
    }

Log in to reply
 

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