leetcode Question: Implement Queue using Stacks

Implement Queue using Stacks

Implement the following operations of a queue using stacks.
  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of 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 toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, 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).

Analysis:


This kind of problem usually requires more than one data structure to implement the other data structure. In this problem, two stacks are enough to implement a queue.

The idea is keep push element into stack 1, then "pop" is called, put all the elements from stack 1 to stack 2. Then pop the top element in stack 2.  If "pop" is called again, not stack 2 is not empty, just pop the top element is enough. If stack 2 is empty, put all the elements in stack 1 to stack 2.  In short, stack 1 is used for "push", stack 2 is used for "pop" and "peek". We do the "move element from stack1 to stack 2" only when stack 2 is empty and "pop" or "peek" is called.


e.g., We call push(1), push(2), push(3), push(4), and push(5), stack 1 is filled all the five elements, then do pop(), since stack 2 is empty, move elements from stack 1 to stack 2, then pop the top element (now is 1) in stack2:
 Then we call push(6), push(7), push(8), push(9), and pop(), pop(), pop(), stack 1 is used for pushing, and stack 2 is used for popping :
Again, we call pop() (now 5 is popped out and no element in stack 2), and a peek() operation is called, stack 2 is empty, so push elements from stack 1 to stack 2, and return the top element as the peek:




Code(C++):

class Queue {

stack<int> st1;
stack<int> st2;

public:
    // Push element x to the back of queue.
    void push(int x) {
        st1.push(x);
    }

    // Removes the element from in front of queue.
    void pop(void) {
        if (!st2.empty()){
            st2.pop();
        }else{
            while (!st1.empty()){
                st2.push(st1.top());
                st1.pop();
            }
            st2.pop();
        }
    }

    // Get the front element.
    int peek(void) {
        if (!st2.empty()){
            return st2.top();
        }else{
            while (!st1.empty()){
                st2.push(st1.top());
                st1.pop();
            }
            return st2.top();
        }
    }

    // Return whether the queue is empty.
    bool empty(void) {
        return (st1.empty() && st2.empty());
    }
};

Code(Python):

class Queue(object):
    def __init__(self):
        """
        initialize your data structure here.
        """
        self.st1 = []
        self.st2 = []
        

    def push(self, x):
        """
        :type x: int
        :rtype: nothing
        """
        self.st1.append(x)
        

    def pop(self):
        """
        :rtype: nothing
        """
        if len(self.st2) == 0:
            while len(self.st1) != 0:
                self.st2.append(self.st1.pop())
        self.st2.pop()
                

    def peek(self):
        """
        :rtype: int
        """    
        if len(self.st2) == 0:
            while len(self.st1) != 0:
                self.st2.append(self.st1.pop())
        return self.st2[-1]
        

    def empty(self):
        """
        :rtype: bool
        """
        return not self.st1 and not self.st2


5 comments:

  1. Through this Digital Marketing Institute in Panchkula, you will become an expert in modules such as SEO, Social Media Marketing, PPC, Analytics, Content, Mobile, and Email Marketing. Our Social Media Marketing and PPC courses in Panchkula have trained end number of students. Work on real-world projects, learn the latest tools, and attend masterclasses led by the Google and Facebook certified team.

    - Get hands-on training on live projects!
    - Upgrade your resume
    - Get prepared for your dream job.
    - 120+ hours of high-quality training.
    - 10+ live projects.
    - 25+ digital marketing tools and platforms.


    Call: +91 9887046666
    Email: info@g-sol.net
    Timings: 10:00 AM TO 12:00 PM
    Location: SCO-9, First Floor, Sector-11, Panchkula, Haryana 134109

    ReplyDelete
  2. Bangaloredigitalmarketing provides the best Digital Marketing courses in bangalore with certification
    and placements in jayanagar, marathahalli
    https://bangaloredigitalmarketing.com/
    https://bangaloredigitalmarketing.com/digital-marketing-courses-in-bangalore/
    https://bengalurudigitalmarketing.blogspot.com/

    ReplyDelete
  3. Amazing post. Informative and knowledgeable content. Keep sharing more stuff like this. Thank you.
    Data Science Institutes in Hyderabad

    ReplyDelete
  4. This is a great post. Your blog is very informative I have learned a lot of information from your blog. We are top Website Development Company in India.



    If anyone is looking for Web Development services contact today: +91 9501406707

    ReplyDelete