Skip to content

5.1   Stack

A stack is a linear data structure that follows the principle of Last-In-First-Out (LIFO).

We can compare a stack to a pile of plates on a table. To access the bottom plate, one must first remove the plates on top. By replacing the plates with various types of elements (such as integers, characters, objects, etc.), we obtain the data structure known as a stack.

As shown in Figure 5-1, we refer to the top of the pile of elements as the "top of the stack" and the bottom as the "bottom of the stack." The operation of adding elements to the top of the stack is called "push," and the operation of removing the top element is called "pop."

Stack's last-in-first-out rule

Figure 5-1   Stack's last-in-first-out rule

5.1.1   Common operations on stack

The common operations on a stack are shown in Table 5-1. The specific method names depend on the programming language used. Here, we use push(), pop(), and peek() as examples.

Table 5-1   Efficiency of stack operations

Method Description Time Complexity
push() Push an element onto the stack (add to the top) \(O(1)\)
pop() Pop the top element from the stack \(O(1)\)
peek() Access the top element of the stack \(O(1)\)

Typically, we can directly use the stack class built into the programming language. However, some languages may not specifically provide a stack class. In these cases, we can use the language's "array" or "linked list" as a stack and ignore operations that are not related to stack logic in the program.

stack.py
# Initialize the stack
# Python does not have a built-in stack class, so a list can be used as a stack
stack: list[int] = []

# Push elements onto the stack
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)

# Access the top element of the stack
peek: int = stack[-1]

# Pop an element from the stack
pop: int = stack.pop()

# Get the length of the stack
size: int = len(stack)

# Check if the stack is empty
is_empty: bool = len(stack) == 0
stack.cpp
/* Initialize the stack */
stack<int> stack;

/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);

/* Access the top element of the stack */
int top = stack.top();

/* Pop an element from the stack */
stack.pop(); // No return value

/* Get the length of the stack */
int size = stack.size();

/* Check if the stack is empty */
bool empty = stack.empty();
stack.java
/* Initialize the stack */
Stack<Integer> stack = new Stack<>();

/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);

/* Access the top element of the stack */
int peek = stack.peek();

/* Pop an element from the stack */
int pop = stack.pop();

/* Get the length of the stack */
int size = stack.size();

/* Check if the stack is empty */
boolean isEmpty = stack.isEmpty();
stack.cs
/* Initialize the stack */
Stack<int> stack = new();

/* Push elements onto the stack */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);

/* Access the top element of the stack */
int peek = stack.Peek();

/* Pop an element from the stack */
int pop = stack.Pop();

/* Get the length of the stack */
int size = stack.Count;

/* Check if the stack is empty */
bool isEmpty = stack.Count == 0;
stack_test.go
/* Initialize the stack */
// In Go, it is recommended to use a Slice as a stack
var stack []int

/* Push elements onto the stack */
stack = append(stack, 1)
stack = append(stack, 3)
stack = append(stack, 2)
stack = append(stack, 5)
stack = append(stack, 4)

/* Access the top element of the stack */
peek := stack[len(stack)-1]

/* Pop an element from the stack */
pop := stack[len(stack)-1]
stack = stack[:len(stack)-1]

/* Get the length of the stack */
size := len(stack)

/* Check if the stack is empty */
isEmpty := len(stack) == 0
stack.swift
/* Initialize the stack */
// Swift does not have a built-in stack class, so Array can be used as a stack
var stack: [Int] = []

/* Push elements onto the stack */
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)

/* Access the top element of the stack */
let peek = stack.last!

/* Pop an element from the stack */
let pop = stack.removeLast()

/* Get the length of the stack */
let size = stack.count

/* Check if the stack is empty */
let isEmpty = stack.isEmpty
stack.js
/* Initialize the stack */
// JavaScript does not have a built-in stack class, so Array can be used as a stack
const stack = [];

/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);

/* Access the top element of the stack */
const peek = stack[stack.length-1];

/* Pop an element from the stack */
const pop = stack.pop();

/* Get the length of the stack */
const size = stack.length;

/* Check if the stack is empty */
const is_empty = stack.length === 0;
stack.ts
/* Initialize the stack */
// TypeScript does not have a built-in stack class, so Array can be used as a stack
const stack: number[] = [];

/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);

/* Access the top element of the stack */
const peek = stack[stack.length - 1];

/* Pop an element from the stack */
const pop = stack.pop();

/* Get the length of the stack */
const size = stack.length;

/* Check if the stack is empty */
const is_empty = stack.length === 0;
stack.dart
/* Initialize the stack */
// Dart does not have a built-in stack class, so List can be used as a stack
List<int> stack = [];

/* Push elements onto the stack */
stack.add(1);
stack.add(3);
stack.add(2);
stack.add(5);
stack.add(4);

/* Access the top element of the stack */
int peek = stack.last;

/* Pop an element from the stack */
int pop = stack.removeLast();

/* Get the length of the stack */
int size = stack.length;

/* Check if the stack is empty */
bool isEmpty = stack.isEmpty;
stack.rs
/* Initialize the stack */
// Use Vec as a stack
let mut stack: Vec<i32> = Vec::new();

/* Push elements onto the stack */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);

/* Access the top element of the stack */
let top = stack.last().unwrap();

/* Pop an element from the stack */
let pop = stack.pop().unwrap();

/* Get the length of the stack */
let size = stack.len();

/* Check if the stack is empty */
let is_empty = stack.is_empty();
stack.c
// C does not provide a built-in stack
stack.kt

stack.zig

Code Visualization

5.1.2   Implementing a stack

To gain a deeper understanding of how a stack operates, let's try implementing a stack class ourselves.

A stack follows the principle of Last-In-First-Out, which means we can only add or remove elements at the top of the stack. However, both arrays and linked lists allow adding and removing elements at any position, therefore a stack can be seen as a restricted array or linked list. In other words, we can "shield" certain irrelevant operations of an array or linked list, aligning their external behavior with the characteristics of a stack.

1.   Implementation based on a linked list

When implementing a stack using a linked list, we can consider the head node of the list as the top of the stack and the tail node as the bottom of the stack.

As shown in Figure 5-2, for the push operation, we simply insert elements at the head of the linked list. This method of node insertion is known as "head insertion." For the pop operation, we just need to remove the head node from the list.

Implementing Stack with Linked List for Push and Pop Operations

linkedlist_stack_push

linkedlist_stack_pop

Figure 5-2   Implementing Stack with Linked List for Push and Pop Operations

Below is an example code for implementing a stack based on a linked list:

linkedlist_stack.py
class LinkedListStack:
    """Stack class based on linked list"""

    def __init__(self):
        """Constructor"""
        self._peek: ListNode | None = None
        self._size: int = 0

    def size(self) -> int:
        """Get the length of the stack"""
        return self._size

    def is_empty(self) -> bool:
        """Determine if the stack is empty"""
        return self._size == 0

    def push(self, val: int):
        """Push"""
        node = ListNode(val)
        node.next = self._peek
        self._peek = node
        self._size += 1

    def pop(self) -> int:
        """Pop"""
        num = self.peek()
        self._peek = self._peek.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """Access stack top element"""
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._peek.val

    def to_list(self) -> list[int]:
        """Convert to a list for printing"""
        arr = []
        node = self._peek
        while node:
            arr.append(node.val)
            node = node.next
        arr.reverse()
        return arr
linkedlist_stack.cpp
/* Stack class based on linked list */
class LinkedListStack {
  private:
    ListNode *stackTop; // Use the head node as the top of the stack
    int stkSize;        // Length of the stack

  public:
    LinkedListStack() {
        stackTop = nullptr;
        stkSize = 0;
    }

    ~LinkedListStack() {
        // Traverse the linked list, remove nodes, free memory
        freeMemoryLinkedList(stackTop);
    }

    /* Get the length of the stack */
    int size() {
        return stkSize;
    }

    /* Determine if the stack is empty */
    bool isEmpty() {
        return size() == 0;
    }

    /* Push */
    void push(int num) {
        ListNode *node = new ListNode(num);
        node->next = stackTop;
        stackTop = node;
        stkSize++;
    }

    /* Pop */
    int pop() {
        int num = top();
        ListNode *tmp = stackTop;
        stackTop = stackTop->next;
        // Free memory
        delete tmp;
        stkSize--;
        return num;
    }

    /* Access stack top element */
    int top() {
        if (isEmpty())
            throw out_of_range("Stack is empty");
        return stackTop->val;
    }

    /* Convert the List to Array and return */
    vector<int> toVector() {
        ListNode *node = stackTop;
        vector<int> res(size());
        for (int i = res.size() - 1; i >= 0; i--) {
            res[i] = node->val;
            node = node->next;
        }
        return res;
    }
};
linkedlist_stack.java
/* Stack class based on linked list */
class LinkedListStack {
    private ListNode stackPeek; // Use the head node as the top of the stack
    private int stkSize = 0; // Length of the stack

    public LinkedListStack() {
        stackPeek = null;
    }

    /* Get the length of the stack */
    public int size() {
        return stkSize;
    }

    /* Determine if the stack is empty */
    public boolean isEmpty() {
        return size() == 0;
    }

    /* Push */
    public void push(int num) {
        ListNode node = new ListNode(num);
        node.next = stackPeek;
        stackPeek = node;
        stkSize++;
    }

    /* Pop */
    public int pop() {
        int num = peek();
        stackPeek = stackPeek.next;
        stkSize--;
        return num;
    }

    /* Access stack top element */
    public int peek() {
        if (isEmpty())
            throw new IndexOutOfBoundsException();
        return stackPeek.val;
    }

    /* Convert the List to Array and return */
    public int[] toArray() {
        ListNode node = stackPeek;
        int[] res = new int[size()];
        for (int i = res.length - 1; i >= 0; i--) {
            res[i] = node.val;
            node = node.next;
        }
        return res;
    }
}
linkedlist_stack.cs
[class]{LinkedListStack}-[func]{}
linkedlist_stack.go
[class]{linkedListStack}-[func]{}
linkedlist_stack.swift
[class]{LinkedListStack}-[func]{}
linkedlist_stack.js
[class]{LinkedListStack}-[func]{}
linkedlist_stack.ts
[class]{LinkedListStack}-[func]{}
linkedlist_stack.dart
[class]{LinkedListStack}-[func]{}
linkedlist_stack.rs
[class]{LinkedListStack}-[func]{}
linkedlist_stack.c
[class]{LinkedListStack}-[func]{}
linkedlist_stack.kt
[class]{LinkedListStack}-[func]{}
linkedlist_stack.rb
[class]{LinkedListStack}-[func]{}
linkedlist_stack.zig
[class]{LinkedListStack}-[func]{}

2.   Implementation based on an array

When implementing a stack using an array, we can consider the end of the array as the top of the stack. As shown in Figure 5-3, push and pop operations correspond to adding and removing elements at the end of the array, respectively, both with a time complexity of \(O(1)\).

Implementing Stack with Array for Push and Pop Operations

array_stack_push

array_stack_pop

Figure 5-3   Implementing Stack with Array for Push and Pop Operations

Since the elements to be pushed onto the stack may continuously increase, we can use a dynamic array, thus avoiding the need to handle array expansion ourselves. Here is an example code:

array_stack.py
class ArrayStack:
    """Stack class based on array"""

    def __init__(self):
        """Constructor"""
        self._stack: list[int] = []

    def size(self) -> int:
        """Get the length of the stack"""
        return len(self._stack)

    def is_empty(self) -> bool:
        """Determine if the stack is empty"""
        return self.size() == 0

    def push(self, item: int):
        """Push"""
        self._stack.append(item)

    def pop(self) -> int:
        """Pop"""
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._stack.pop()

    def peek(self) -> int:
        """Access stack top element"""
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._stack[-1]

    def to_list(self) -> list[int]:
        """Return array for printing"""
        return self._stack
array_stack.cpp
/* Stack class based on array */
class ArrayStack {
  private:
    vector<int> stack;

  public:
    /* Get the length of the stack */
    int size() {
        return stack.size();
    }

    /* Determine if the stack is empty */
    bool isEmpty() {
        return stack.size() == 0;
    }

    /* Push */
    void push(int num) {
        stack.push_back(num);
    }

    /* Pop */
    int pop() {
        int num = top();
        stack.pop_back();
        return num;
    }

    /* Access stack top element */
    int top() {
        if (isEmpty())
            throw out_of_range("Stack is empty");
        return stack.back();
    }

    /* Return Vector */
    vector<int> toVector() {
        return stack;
    }
};
array_stack.java
/* Stack class based on array */
class ArrayStack {
    private ArrayList<Integer> stack;

    public ArrayStack() {
        // Initialize the list (dynamic array)
        stack = new ArrayList<>();
    }

    /* Get the length of the stack */
    public int size() {
        return stack.size();
    }

    /* Determine if the stack is empty */
    public boolean isEmpty() {
        return size() == 0;
    }

    /* Push */
    public void push(int num) {
        stack.add(num);
    }

    /* Pop */
    public int pop() {
        if (isEmpty())
            throw new IndexOutOfBoundsException();
        return stack.remove(size() - 1);
    }

    /* Access stack top element */
    public int peek() {
        if (isEmpty())
            throw new IndexOutOfBoundsException();
        return stack.get(size() - 1);
    }

    /* Convert the List to Array and return */
    public Object[] toArray() {
        return stack.toArray();
    }
}
array_stack.cs
[class]{ArrayStack}-[func]{}
array_stack.go
[class]{arrayStack}-[func]{}
array_stack.swift
[class]{ArrayStack}-[func]{}
array_stack.js
[class]{ArrayStack}-[func]{}
array_stack.ts
[class]{ArrayStack}-[func]{}
array_stack.dart
[class]{ArrayStack}-[func]{}
array_stack.rs
[class]{ArrayStack}-[func]{}
array_stack.c
[class]{ArrayStack}-[func]{}
array_stack.kt
[class]{ArrayStack}-[func]{}
array_stack.rb
[class]{ArrayStack}-[func]{}
array_stack.zig
[class]{ArrayStack}-[func]{}

5.1.3   Comparison of the two implementations

Supported Operations

Both implementations support all the operations defined in a stack. The array implementation additionally supports random access, but this is beyond the scope of a stack definition and is generally not used.

Time Efficiency

In the array-based implementation, both push and pop operations occur in pre-allocated contiguous memory, which has good cache locality and therefore higher efficiency. However, if the push operation exceeds the array capacity, it triggers a resizing mechanism, making the time complexity of that push operation \(O(n)\).

In the linked list implementation, list expansion is very flexible, and there is no efficiency decrease issue as in array expansion. However, the push operation requires initializing a node object and modifying pointers, so its efficiency is relatively lower. If the elements being pushed are already node objects, then the initialization step can be skipped, improving efficiency.

Thus, when the elements for push and pop operations are basic data types like int or double, we can draw the following conclusions:

  • The array-based stack implementation's efficiency decreases during expansion, but since expansion is a low-frequency operation, its average efficiency is higher.
  • The linked list-based stack implementation provides more stable efficiency performance.

Space Efficiency

When initializing a list, the system allocates an "initial capacity," which might exceed the actual need; moreover, the expansion mechanism usually increases capacity by a specific factor (like doubling), which may also exceed the actual need. Therefore, the array-based stack might waste some space.

However, since linked list nodes require extra space for storing pointers, the space occupied by linked list nodes is relatively larger.

In summary, we cannot simply determine which implementation is more memory-efficient. It requires analysis based on specific circumstances.

5.1.4   Typical applications of stack

  • Back and forward in browsers, undo and redo in software. Every time we open a new webpage, the browser pushes the previous page onto the stack, allowing us to go back to the previous page through the back operation, which is essentially a pop operation. To support both back and forward, two stacks are needed to work together.
  • Memory management in programs. Each time a function is called, the system adds a stack frame at the top of the stack to record the function's context information. In recursive functions, the downward recursion phase keeps pushing onto the stack, while the upward backtracking phase keeps popping from the stack.
Feel free to drop your insights, questions or suggestions