GeeksforGeeks » Algorithms

Implement queue using stacks

(3 posts)
[closed]
  • Started 2 years ago by Shekhu
  • Latest reply from geeksforgeeks

Tags:

  1. Shekhu
    guest
    Posted 2 years ago #

    How will implement queue using 2 stacks such that enqueue and dequeue operations are efficient

  2. geek4u
    guest
    Posted 2 years ago #

    Here is a pseudo code using two stacks. Let two stacks be S1 and S2 and queue is Q.

    For enqueue operation, push in buffer stack S1.
    For dequeue operation, if S2 is not empty then pop and return top element of S2, otherwise push everything from S1 to S2 and then pop and return the top element of S2

    void enQueue(Q,  x)
    {
        push (S1,  x);
    }
    
    void deQueue(Q)
    {
       if (isStackEmpty(52))
       {
         if (isStackEmpty(S1))
         {
              print(”Q is empty”);
              return;
         }
         else
         {
             while (!(isStackEmpty(S1)))
             {
                  x = pop(S1);
                 push(S2,  x)
             }
         }     
    
         x = pop (S2);
         return x;
    }
    
  3. GeeksforGeeks
    Key Master
    Posted 2 years ago #

    This has been published. Please see http://geeksforgeeks.org/?p=5009

    Thanks all for your contribution.


Topic Closed

This topic has been closed to new replies.

RSS feed for this topic