4.2Stack with a Linked List
Pop: removing an element
pop removes the top element of the stack and returns its value. The top is the head of the list, so pop is the same as deleting from the head; the only extra work is handing the removed node's value back to the caller. In C this lesson also shows how to free the node's memory in the right order.
1Idea
First the stack is checked for being empty. Trying to remove an element from an empty stack is an underflow. In C the function returns false; Java throws IllegalStateException and Python raises IndexError.
If the stack is not empty there are four steps. Keep the address of the top node in temp. Write its value into *value. Move top to the next node, temp->next. Finally give temp back with free.
In C, free is called after the value is read and top has moved. If you call it earlier, you read from freed memory. If you never call it, the node leaves the stack but its memory is never returned; that is a memory leak.
Java and Python have no free. The value goes into a local variable and top moves forward; no reference to the old top is left, so the garbage collector reclaims it.
2Step by step
The drawing pops a stack holding 30, 20 and 10. The top is on the left, at the head of the list. At each step the matching line of code lights up.
- Start. top points to 30. This is the element that leaves.
- The stack is not empty. The address of the top node is saved in
temp; oncetopchanges,tempis the only way to reach that node. - The node's value, 30, is read so it can be handed to the caller.
topmoves to the next node, 20. 30 is no longer part of the stack, buttempstill points to it.- In C the memory of 30 is returned with free. Java and Python have no such line; the garbage collector reclaims the node.
- Result: 20 on top, 10 at the bottom. The function hands back 30; in C it returns
true.
struct Node { int data; struct Node* next;}; struct Stack { struct Node* top;}; bool pop(struct Stack* s, int* value) { if (s->top == NULL) return false; // empty stack struct Node* temp = s->top; *value = temp->data; s->top = temp->next; free(temp); return true;}class Node { int data; Node next; Node(int data) { this.data = data; }} class LinkedStack { Node top = null; int pop() { if (top == null) throw new IllegalStateException("stack is empty"); int value = top.data; top = top.next; return value; }}class Node: def __init__(self, data): self.data = data self.next = None class LinkedStack: def __init__(self): self.top = None def pop(self): if self.top is None: raise IndexError("stack is empty") value = self.top.data self.top = self.top.next return valueThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Independent of the number of elements: one comparison, a few assignments and one free.
Only one helper pointer is used.
If the top were at the end of the list, pop would be O(n) like deleting from the end. That is why the top is the head of the list.
4Common mistake
The most common mistake is reading a node's fields after freeing it:
free(s->top);*value = s->top->data; // freed memorys->top = s->top->next;After free, s->top is a dangling pointer. The code sometimes seems to work, sometimes reads a wrong value or crashes. The right order: save it in temp, read the value, move top, call free last. Leaving out the free line is a mistake too: every pop loses one node's worth of memory.
5Try it
What happens if the free(temp) line is missing from pop in C?
The answer is B. top still moves forward and the value is still correct. But the removed node's memory is never returned and can no longer be reached. The longer the program runs, the more memory it uses.
Show the answer
The answer is B. top still moves forward and the value is still correct. But the removed node's memory is never returned and can no longer be reached. The longer the program runs, the more memory it uses.
What does the Python version do if pop is called on an empty stack?
The answer is B. The first line checks whether top is None. Nothing can be removed from an empty stack (underflow); the method reports it with an error.
Show the answer
The answer is B. The first line checks whether top is None. Nothing can be removed from an empty stack (underflow); the method reports it with an error.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.