An integer stack starts empty, and the eight operations in the table run in order from top to bottom. A pop removes and returns the top element. A peek returns the top element without removing it. A push returns nothing. Fill in the value each pop or peek returns, the top element after each operation, and the number of elements on the stack after each operation.
Unlock full course notes by signing up
A stack is a linear collection in which push and pop both act at one end only, called the of the stack. Calling pop on an empty stack is an error called stack , and calling push on a fixed-capacity stack that is already full is an error called stack .
A stack is implemented with a dynamic array that doubles its capacity when full, and the top of the stack is kept at the end of the array (the highest occupied index). Which of the following statements about this stack are true? Select all that apply.
If five values are pushed and then five pops follow, the values come out in the order they were pushed.
Each pop returns the element that was pushed most recently among those still on the stack.
Moving the top to index 0 of the array would keep both push and pop at O(1) time per operation.
Calling peek on a non-empty stack returns the top element and reduces the stack's size by one.
Push runs in amortized O(1) time, even though an occasional push triggers a full array copy.
Order in which call-stack frames are popped
When a function is called, a frame for it is pushed onto the program's call stack, and when the function returns, its frame is popped. Running main() in the Python program below pushes and pops several frames. Arrange the frames in the order in which they are popped from the call stack, first popped at the top.
Evaluating a postfix expression with a stack
A program evaluates the postfix (reverse Polish) expression below by reading tokens from left to right with an initially empty stack. Each number is pushed. Each binary operator pops two values, applies the operator to them, and pushes the result. Division here is exact, with no rounding.
Give the final value left on the stack, as an integer, and the maximum number of elements the stack holds at any moment during the evaluation, as an integer.
Undo and redo with two stacks
A simple text editor implements undo and redo with two stacks. Every typing action appends one character to the end of the document and pushes that character onto the undo stack. The editor follows three rules: