Let and be two stacks. has capacity of elements. has capacity of elements. already has elements: , and , whereas is empty, as shown below.
Only the following three operations are available:
- PushToS2: Pop the top element from S1 and push it on S2.
- PushToS1: Pop the top element from S2 and push it on S1.
- GenerateOutput: Pop the top element from S1 and output it to the user.
Note that the pop operation is not allowed on an empty stack and the push operation is not allowed on a full stack.
Which of the following output sequences can be generated by using the above operations?
View worked solution
Answer: B;C;D
To determine which sequences can be generated, we trace the operations while respecting the capacity constraints: has capacity and has capacity .
- Option A () is impossible:
To output first, we must remove and from . Since we cannot output them yet, they must be moved to . However, has a capacity of only . After moving and to , becomes full. Thus, cannot be moved, blocking access to . - Option B () is possible:
PushToS2twice: ,GenerateOutput: Outputs . ()PushToS1: ,GenerateOutput: Outputs . ()PushToS1: ,GenerateOutput: Outputs . ()GenerateOutput: Outputs . ()
- Option C () is possible:
GenerateOutput: Outputs . (, )PushToS2: ,GenerateOutput: Outputs . (, )PushToS2: ,PushToS1: ,GenerateOutput: Outputs . (, )PushToS1: ,GenerateOutput: Outputs . ()
- Option D () is possible:
PushToS2: ,GenerateOutput: Outputs . ()GenerateOutput: Outputs . ()PushToS1: ,GenerateOutput: Outputs . ()GenerateOutput: Outputs . ()
Free practice · Your answers on this page are not saved.
