Suppose you have a stack in which the values 1 through 5 must be pushed on the s
ID: 3678779 • Letter: S
Question
Suppose you have a stack in which the values 1 through 5 must be pushed on the stack in that order, but that an item on the stack can be popped and printed at anytime. So for example, the operations
s.push(1); s.push(2); print s.pop();
s.push(3); s.push 4); print s.pop();
s.push(5); print s.pop(); print s.pop(); print s.pop();
produces 2 4 5 3 1. Based on the constraints mentioned above, give the list of operations that would produce the following sequence, If it is not possible, state so.
1 3 5 4 2
Explanation / Answer
Stack is Last In First Out data structure.
The operations required to stack to product 1 3 5 4 2
List of stack operations to display 1 3 5 4 2
s.push(1); // The stack contains 1 ,S={1}
s.pop(); //Pop removes 1 , stack is empty,S={}
s.push(2); // push=2,the stack contains ,S={2}
s.push(3); // push=3,the stack contains ,S={2,3}
s.pop(); //Pop removes 3 , stack ,S={2}
s.push(4); // push=4,the stack contains ,S={2,4}
s.push(5); // push=5,the stack contains ,S={2,4,5}
s.pop(); //Pop removes 5 , stack ,S={2,4}
s.pop(); //Pop removes 4 , stack ,S={2}
s.pop(); //Pop removes 2 , stack is empty,S={}
Pop elmements are 1 3 5 4 2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.