Queue using Two Stacks

  • + 0 comments

    Thanks to hackerrank4021 , Java solution is below.

    import java.io.*;
    import java.util.*;
    
    /*
    a. For insert, insert into stack1.
    b. For deque, deque from stack2. If it is not empty transfer from 1 to 2 and deque from 2.
    c. For peek, show peek of stack2. If empty transfer from 1 to 2 and then peek from 2.
    */
    
    public class Solution {
    
        public static Stack<Integer> sta1 = new Stack();
        public static Stack<Integer> sta2 = new Stack();
        
        public static void main(String[] args) {
            /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
            
            // only below is poss in stacks
            // sta1.removeLast();
            Scanner sc = new Scanner(System.in);
            int noQ = sc.nextInt();
            
            while (noQ-- > 0) {
                switch (sc.next()) {
                    case "1":
                        insertQueue(sc.nextInt());
    
                        // print queue top
                        // printQueueHead();
            
                        break;
    
                    case "2":
                        deQueue();
                        break;
    
                    case "3":
                        printQueueHead();
                        break;
    
                    case "q":
                        return;
    
                    default:
                        System.out.println("Invalid input!");
                        break;
                }
            }
        }
        
        public static void insertQueue(int item) {
            sta1.add(item);
        }
        
        public static void transfer() {
            if(sta1.size() == 0)
                return;
            do {
                sta2.push(sta1.pop());
            }while(sta1.size() > 0);
        }
            
        public static Integer deQueue() {
    
            if(sta2.size() == 0) {
                if(sta1.size() == 0) {
                    return null;
                }
                transfer();
            }
            
            return sta2.pop();
        }
        
        // sta1 s last element is the queue head
        public static void printQueueHead(){
            
            if(sta2.size() == 0) {
                if(sta1.size() == 0) {
                    return;
                }
                transfer();
            }
            
            System.out.println(sta2.peek());
        }
    }