You are viewing a single comment's thread. Return to all comments →
Getting TLE in the code below. Any Suggestions?
import java.util.Scanner; import java.util.Stack; public class Solution { private static Stack<Integer> st1; private static Stack<Integer> st2; private static void enqueue(int x) { while (!st1.isEmpty()) { st2.push(st1.pop()); } st2.push(x); while (!st2.isEmpty()) { st1.push(st2.pop()); } } private static int dequeue() { if (st1.isEmpty()) { return -1; } return st1.pop(); } private static int display(){ if (st1.isEmpty()) { return -1; } return st1.peek(); } public static void main(String[] args) { st1 = new Stack<>(); st2 = new Stack<>(); Scanner sc = new Scanner(System.in); int n=sc.nextInt(); while(n>0) { int ch=sc.nextInt(); switch (ch) { case 1: enqueue(sc.nextInt()); n--; break; case 2: dequeue(); n--; break; case 3: System.out.println(display()); n--; break; default: break; } } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
Getting TLE in the code below. Any Suggestions?