0

For this simple problem, I need to find the value(s) of stack1 and in order, if any. When it comes to the stack, the principle is LIFO (last in, first out) or FILO (first in, last out). And the reason stacks are used is to reverse the data, and displaying it in reverse order.

Stack<Integer> stack1 = new Stack<Integer>();
stack1.push (2);
stack1.push(5);
stack1.push (stack1.pop() - stack1.pop());
stack1.push(8);

The question above made me think, if we were to use the principle, should the answer be this: 8, 3, 5, 2.

8 being the last value being the start, then the next value being 3, from taking 5 and 2 (the "pop" being the deletion at the "head"). Then the next two values being 5 and 2. Would that be the right answer, or did I got the incorrect answer?

Raudel Ravelo
  • 648
  • 2
  • 6
  • 24
JF141996
  • 15
  • 5

2 Answers2

0

The Stack is a LIFO (last in first out). Look at it from the point of view of the first element you put in. You should also check this out what is the basic difference between stack and queue?.

As for the example, the answer is 8 and 3 only because when you calculated the 3 as stack.pop() - stack.pop() you deleted the 5 and the 2 from the stack, so they won´t be there anymore.

Raudel Ravelo
  • 648
  • 2
  • 6
  • 24
0

Stack stack1 = new Stack(); []

stack1.push (2); [2]

stack1.push(5); [2,5]

stack1.push (stack1.pop() [2] - stack1.pop() [] ); [3]

stack1.push(8); [3,8]

JasonB
  • 6,243
  • 2
  • 17
  • 27