algoritmauzmanı
Sign in
TREN
4.2Stack with a Linked List
Lesson 4.2.3

Pop: removing an element

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.

What you will learn
  • What happens when you pop an empty stack and how that is prevented
  • Why the top node is kept in a temporary pointer and when is called
  • How pop is written in C, Java and Python, and why it is
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

First the stack is checked for being empty. Trying to remove an element from an empty stack is an . 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 to the next node, temp->next. Finally give temp back with .

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 .

Java and Python have no free. The value goes into a local variable and top moves forward; no 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.

NULL30?0x2c1020?0x1a9010?0x1a40toptemp
  1. Start. points to 30. This is the element that leaves.
  2. The stack is not empty. The address of the top node is saved in temp; once top changes, temp is the only way to reach that node.
  3. The node's value, 30, is read so it can be handed to the caller.
  4. top moves to the next node, 20. 30 is no longer part of the stack, but temp still points to it.
  5. In C the memory of 30 is returned with . Java and Python have no such line; the garbage collector reclaims the node.
  6. 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 value

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(1)

Independent of the number of elements: one comparison, a few assignments and one free.

Memory
O(1)

Only one helper pointer is used.

If the top were at the end of the list, pop would be 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 . 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?

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?

Show the answer

The answer is B. The first line checks whether top is None. Nothing can be removed from an empty stack (); 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.