Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, May 10, 2017

Queue Using Two Stacks


Here i am taking 2 stack objects of stack class of java (to pure use to stack)
Adding value on input 1 and deleting on 2 ,showing 1st value at 3rd.

Now i am taking stack1 to push objects and when 2 /3 comes as input then we are copying data into another stack and order from lifo(pushing to stack1) - lifo(copy data to stack 2) =FIFO .
Hence while printing just peeking that value

Code :
import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
int n;
        Scanner in=new Scanner(System.in);
        n=in.nextInt();
        Stack<Integer> stack1=new Stack<Integer>();
        Stack<Integer> stack2=new Stack<Integer>();
          while(n-->0)
              {
              int x=in.nextInt();
              if(x==1)
                  {
                  int data=in.nextInt();
                  stack1.push(data);
              }
              else if (x==2)
                  {
                  if(stack2.empty())
                      {
                      while(!stack1.empty())
                      stack2.push(stack1.pop());
                  }
                  stack2.pop();
                     
              }
              else if(x==3)
                  {
                   if(stack2.empty())
                      {
                      while(!stack1.empty())
                      stack2.push(stack1.pop());
                  }
                  System.out.println(stack2.peek());
              }
          }
    }
}

0 Comments:

Post a Comment

Stats