Blogs Hub

by Sumit Chourasia | Oct 03, 2020 | Category :coding | Tags : algorithm data-structure easy leetcode stack

Implement Queue using Stacks - Stack - Easy - LeetCode

Implement Queue using Stacks - Stack - Easy - LeetCode

Implement the following operations of a queue using stacks.

push(x) -- Push element x to the back of the queue.
pop() -- Removes the element from in front of the queue.
peek() -- Get the front element.
empty() -- Return whether the queue is empty.
Notes:

You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
 

Example 1:

Input
["MyQueue", "push", "push", "peek", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 1, 1, false]

Explanation
MyQueue myQueue = new MyQueue();
myQueue.push(1);
myQueue.push(2);
myQueue.peek(); // return 1
myQueue.pop(); // return 1
myQueue.empty(); // return False
 

Constraints:

1 <= x < 10
At most 100 calls will be made to push, pop, peek, and empty.

public class MyQueue {

    Stack<int> stack1;
    Stack<int> stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<int>();
        stack2 = new Stack<int>();
    }
    
    /** Push element x to the back of queue. */
    public void Push(int x) {
        stack1.Push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int Pop() {
        if(stack2.Count()<1){
            while(stack1.Count()>0){
                stack2.Push(stack1.Pop());
            }
        }
        
        return stack2.Pop();
    }
    
    /** Get the front element. */
    public int Peek() {
        if(stack2.Count<1){
            while(stack1.Count()>0){
                stack2.Push(stack1.Pop());
            }
        }
        return stack2.Peek();
    }
    
    /** Returns whether the queue is empty. */
    public bool Empty() {
        return stack1.Count()<1 && stack2.Count()<1;
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.Push(x);
 * int param_2 = obj.Pop();
 * int param_3 = obj.Peek();
 * bool param_4 = obj.Empty();
 */

Time Complexity: O(n)

Space Complexity: O(n)