Lecture 4
Stack quiz
Answer each question to see whether you got it right and why. Your answers are saved in this browser.
A stack is which kind of structure?
The last item pushed is the first one popped, because every insertion and removal happens at the top.
In a stack, all insertions and deletions are done at one end, called the top.
That restriction is what defines a stack. A queue (Lecture 5) uses two ends.
You can read the third element from the top of a stack directly, without popping anything.
Access is by position in order of insertion, and only the top is visible. To reach a lower element you must pop everything above it.
Empty stack, then
push(4), push(9), pop(), push(2), push(7), pop(). Type the two values returned by the pops, in order, separated by a space.The first pop removes 9 (pushed last at that point). Then 2 and 7 are pushed, and the second pop removes 7.
Same sequence:
push(4), push(9), pop(), push(2), push(7), pop(). Type the final stack from top to bottom, separated by spaces.Trace: [4] → [9,4] → [4] → [2,4] → [7,2,4] → [2,4]. Top to bottom: 2, 4.
Which of these is not a typical use of a stack?
Serving jobs in arrival order is first in, first out: that's a queue. The others all need the most recent item first.
You push the letters of
"ABC"one by one, then pop until empty. What is printed?The last letter pushed (C) comes out first. Push-all-then-pop-all always reverses a sequence.
What does
stackTop(el)do?stackTopis a read-only peek; it's declaredconst.pop(el)is the one that also removes.In the slides' ADT,
popreturns the removed element through a reference parameter (pop(Type &)).The caller writes
s.pop(x);and then usesx. The slides' GeeksforGeeks-style example uses apop()that returns the value instead.Popping from an empty stack is called:
Underflow is removing from an empty stack. Overflow is pushing onto a full one.
Both the array stack and the linked stack in the slides provide
stackIsFull().Only the array stack has a fixed capacity.
StackLhas nostackIsFull()because it grows one node at a time.In the array-based stack, what value of
topmeans the stack is empty?topis the index of the top element. With no elements it's-1, so the first push uses index 0.A
Stacktwas created with capacityMaxSize. When is it full?Valid indexes are
0toMaxSize - 1. Whentopis the last valid index, there's no room for another push.What capacity does
Stackt<int> s;get?The constructor is declared
Stackt(int nelements = 128);, so with no argument the capacity is 128.Which line correctly pushes
vonto the array stack (after the full check)?++topmoves to the next free slot first, then stores. Withtop = -1it writesstack[0].top++would writestack[-1].What does this print?
Stackt<int> s(5); int x, y; s.push(10); s.push(20); s.push(30); s.pop(x); s.stackTop(y); cout << x << " " << y;Three pushes give
stack = [10, 20, 30]withtop = 2. Pop readsstack[2] = 30and setstop = 1.stackTopreadsstack[1] = 20without movingtop.popin the array stack erases the value from the array slot.It only decrements
top. The old value stays in the slot but is no longer part of the stack, and the next push overwrites it.Why does
Stacktdefine its own copy constructor?The default copy only copies the
stackpointer, so both objects would share one array and both destructors woulddelete[]it. The slides' version allocates a new array and copies the elements (a deep copy).Why does
Stackt.hend with#include "Stackt.cpp"?Template code is only compiled when a type like
Stackt<int>is used, so the definitions must be visible in the header. Lecture 3'sListdoes the same.What is wrong with this
pushfrom the slides?template <class T> void Stack<T>::push(T k) { if (isFull()) { cout << "Stack is full\n"; } cout << "Inserted element " << k << endl; top = top + 1; st[top] = k; }The
ifonly prints a message. Execution continues, sotopbecomesSIZEandst[SIZE]is out of bounds. It needs areturn;inside theif.In the linked stack,
toppoints to:Insert and delete at the head of a singly linked list are both O(1), so the head is the top.
Which two lines push the new node
pnew(data already set), in the right order?Link the new node to the old top first, then move
top. In the reverse orderpnew->nextwould point atpnewitself and the rest of the stack is lost.Which is a correct order for linked-stack pop?
Read the value and keep the old node, move
top, then free the old node. Anything that reads a node afterdeleteis undefined behaviour.A linked stack needs more memory per element than an array stack, but it is more flexible in size.
Each element carries a
nextpointer. In return, it never has a fixed capacity, so there is no overflow until the heap runs out.Pushing onto an empty linked stack needs a special case.
With
top == nullptr,pnew->next = topsets the new node'snexttonullptr, andtop = pnewmakes it the only node. The general code already works.What should
~StackL()do?The object only holds the
toppointer. Deleting justtopor resetting it leaks every other node.While checking brackets, you read a right symbol and the stack is empty. What does it mean?
A closer with nothing open can't match anything, so the algorithm sets
balanced = false.If every closer matched but the stack is not empty at the end of the input, the text is still balanced.
Leftover openers were never closed, for example
((a). The algorithm checks for an empty stack at the end.{ [ ( a + b ) * ( c - d ) ] }is balanced. If the final}is replaced with], why does the check fail?After the inner brackets close, only
{is left. Popping it for]is a mismatch.Check
{ [ ( ) ] }with a stack. Type the stack after the third bracket, bottom to top, with no spaces. (Practice sheet Q18)The first three brackets are all openers, so they're pushed:
{,{[,{[(. The rest then pop(,[,{in turn and the stack ends empty.Check
{ [ ( ] ) }. At which position (starting at 1, spaces don't count) is the first error? (Practice sheet Q18)After
{[(the 4th bracket is], but the top is(, which expects). Stop at position 4.What is the postfix form of
(A+B) * (C-(D+E))?A B +is the left factor.C D E + -isC - (D+E). The final*multiplies them.Why does postfix notation not need parentheses?
An operator is applied as soon as it is read, to the two most recent operands. There's never a question of which operation goes first.
Evaluating
8 2 -with a stack: you pop2first, then8. What is pushed?The first pop is the right operand and the second is the left, so it's
8 - 2 = 6.Evaluate the postfix expression
2 3 + 2 4 1 + - *.2 3 += 5;4 1 += 5;2 5 -= -3;5 -3 *= -15. It's the postfix form of(2+3) * (2-(4+1)).After the last token, a valid postfix expression leaves exactly one value on the stack.
That value is the result. Zero values or more than one mean the expression was malformed.
Evaluate
18 6 2 / - 3 4 + *with a stack. Type the stack, bottom to top, right after the/token. (Practice sheet Q19)/pops 2 (right) then 6 (left) and pushes6 / 2 = 3, leaving [18, 3].Same expression
18 6 2 / - 3 4 + *: what is on the stack after the-token? (Practice sheet Q19)-pops 3 (right) then 18 (left) and pushes18 - 3 = 15.Same expression
18 6 2 / - 3 4 + *: what is the final result? (Practice sheet Q19)After
3 4 +the stack is [15, 7], and*gives 105.Using the stack algorithm (self-study), what is
A + B * C - Din postfix?*binds tighter, soB C *comes first. When-arrives it pops*and then+(equal precedence), givingA B C * + D -.Converting 300 to hexadecimal by pushing
n % 16and dividing, then popping everything. What is printed?300 % 16 = 12 (C), 18 % 16 = 2, 1 % 16 = 1. They're pushed as C, 2, 1 and popped as 1, 2, C.
When searching a maze with a stack, what do you do at a dead end?
Popping returns you to the previous position, which then tries its next untried direction.
The slides say the maze search will later be done recursively with the system stack. What is that algorithm called?
Recursion uses the run-time stack, and searching deep before backtracking is Depth First Search (DFS).
Each function call pushes a frame on the run-time stack, and returning from the function pops it.
The most recently called function returns first: LIFO. Infinite recursion keeps pushing frames until the call stack overflows.
Array stack
[3, 7](7 on top),out = 0. Runpeek(out). Type the return value andout, separated by a space. (Practice sheet Q16)bool pop(int& out) { if (empty()) return false; out = data[topIndex--]; return true; } bool peek(int& out) const { if (empty()) return false; out = data[topIndex]; return true; }peekreadsdata[topIndex]= 7 and returns true. The stack is unchanged.Using the Q16 code above, after the
peek, runpop(out)three times. Type the value ofoutafter each pop, separated by spaces. (Practice sheet Q16)The pops return (true, 7) and (true, 3). The third pop finds the stack empty, returns false and leaves
outunchanged at 3.In the Q16 code above, a failed
popon an empty stack setsoutback to 0. (Practice sheet Q16)It returns false before touching
out, sooutkeeps its previous value. That's the sheet's rule: a failed operation leaves the output argument unchanged.Linked stack with 11 on top and 4 below it. Pop three times with the code below. What is
(return, out, topNode)after the third pop? (Practice sheet Q17)bool pop(int& out) { if (!topNode) return false; Node* old = topNode; out = old->value; topNode = old->next; delete old; return true; }The states are (true, 11, node 4), (true, 4, null), (false, 4, null). The third pop returns false and leaves
outat 4.In the Q17 code above, why is
oldneeded? (Practice sheet Q17)Once
topNode = old->nextruns, nothing else points at the old top. Withoutoldyou couldn't free it, and deletingtopNodefirst would makeold->nextunreadable.Maze (S at (1,1), G at (4,5)); try right, down, left, up; mark cells visited when pushed. Type the two cells that get popped, in order, as
(r,c) (r,c). (Practice sheet Q20)1 2 3 4 5 1 S . . # # 2 . # # # # 3 . . . # # 4 # # . . GGoing right pushes (1,1), (1,2), (1,3). From (1,3) right and down are walls, so it's popped. (1,2) has no unvisited open neighbour (down is a wall), so it's popped too. Then (1,1) goes down.
Using the Q20 maze above, what is the final path from S to G? (Practice sheet Q20)
After backtracking from row 1, the search goes down column 1, right along row 3, down to (4,3) and right to G. The stack from bottom to top is that path.