Data Structures and Algorithms

Homework 05

(adapted from Pham Bao Son's DSA-09s2)

Question 1.
Describe the output of the following series of stack operations: push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop() .

Question 2.
Describe the output for the following sequence of queue operations: enqueue(5), enqueue(3), dequeue(), enqueue(2), enqueue(8), dequeue(), dequeue(), enqueue(9), enqueue(1), dequeue(), enqueue(7), enqueue(6), dequeue(), dequeue(), enqueue(4), dequeue(), dequeue() .

Question 3.
Give a recursive or iterative algorithm for removing all the elements in a stack.

Question 4.
Suppose you have a stack S containing n elements and a queue A that is initially empty. Describe how you can use Q to scan S to see if it contains a certain element x, with the addtional constraint that your algorithm must return the elements back to S in their original order. You may not use an array or linked list – only S and Q and a constant number of reference variables.