What is printed in each of the lines below? Stack<Integer> s = new Stack<Integer
ID: 3582626 • Letter: W
Question
What is printed in each of the lines below?
Stack<Integer> s = new Stack<Integer>();
s.push(3);
s.push(5);
s.pop(); // line 1- what is returned?
s.push(2);
s.push(4);
s.pop(); // line 2- what is returned?
s.pop(); // line 3- what is returned?
s.push(6);
s.push(8);
s.push(1);
s.push(7);
s.peek(); // line 4- what is returned?
s.pop(); // line 5- what is returned?
s.push(s.pop());
s.pop(); // line 6- what is returned?
s.pop(); // line 7- what is returned?
s.pop(); // line 8- what is returned?
Explanation / Answer
Here first Stack Object s is created.
s.push(3) - add 3 to stack
Stack = 3
s.push(5) - add 5 to stack
Stack = 5,3
s.pop() - it will take out the top element of stack which is 5 hence 5 will be returned and now Stack is 3
s.push(2) -add 2 to stack
Stack = 2,3
s.push(4) - add 4 to stack
Stack = 4,2,3
s.pop() - takes out the top element of stack which is 4 , hence 4 will be returned and now stack becomes Stack = 2,3
s.pop() - takes out the top element of stack which is 2, hence 2 will be returned and now stack becomes Stack = 3
s.push(6) - add 6 to stack
Stack = 6,3
s.push(8) - add 8 to stack
Stack = 8,6,3
s.push(1) - add 1 to stack
Stack = 1,8,6,3
s.push(7) - add 7 to stack
Stack = 7,1,8,6,3
s.peek() - this method is used to check object at top of stack but doesnot remove it hence it will return 7 and stack remains same
Stack = 7,1,8,6,3
s.pop() - it takes out top element of stack , hence 7 will be returned and now stack becomes Stack = 1,8,6,3
s.push(s.pop()) - it will push the current top element to stack as inside push we have s.pop() which returns 1 and makes stack 8,6,3 and the push 1 to stack hence stack becomes Stack = 1,8,6,3
s.pop() - it takes out the top element of stack hence will return 1 and now stack becomes Stack = 8,6,3
s.pop() - it takes the top element of stack hence will return 8 and now stack becomes Stack = 6,3
s.pop()- it takes the top element of stack hence will return 6 and now stack becomes Stack 3.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.