JAVA STACK .......EMPTY STACK EXCEPTION...... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

JAVA STACK .......EMPTY STACK EXCEPTION......

/* 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. The first line of input contains an integer,N . The next N lines each contain an above mentioned query. (It is guaranteed that each query is valid.) */ import java.io.*; import java.util.*; public class stack { static void Sta_push( Stack <Integer> stack, Stack <Integer> stack2,int x) { if (stack.isEmpty()) { // if stack is empty, insert the number in both // stacks stack.add(x); stack2.add(x); } else { // check if number in Stack(track) is bigger than x // which ever is bigger, insert it into Stack int a = stack2.peek(); stack2.add(Math.max(a, x)); stack.add(x); // insert it into main stack. } } static int getMax(Stack <Integer> stack2) { return( (Integer)stack2.peek()); } static void Sta_pop(Stack<Integer> stack, Stack<Integer> stack2) { if (!stack.isEmpty()) { stack.pop(); stack2.pop(); } } public static void main(String[] args) { Stack<Integer> stack = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); Scanner sc= new Scanner(System.in); int N= sc. nextInt(); for(int i= 1;i<=N;i++) { int q= sc.nextInt(); //System.out.println(q); //System.out.println(r); if(q==1) { int r = sc.nextInt(); Sta_push(stack, stack2,r); } if(q==2); Sta_pop(stack , stack2); if(q==3) { int c= getMax(stack2); System.out.println(c); } }}

26th Jul 2018, 5:06 PM
Smriti Rastogi
Smriti Rastogi - avatar
1 Answer
+ 2
Not sure what you're asking but if (!stack.isEmpty()) { stack.pop(); stack2.pop(); } is this causing your error? You're popping off stack2 while only checking stack1
1st Sep 2018, 12:00 PM
Steven Trippier
Steven Trippier - avatar