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

Creating a linked-list stack

An array stack works with a fixed capacity and cannot take new elements once it is full. A built on a linked list allocates a separate for each element, so it grows for as long as memory lasts. In this lesson you set up the structure and write the empty stack and the emptiness check.

What you will learn
  • Which fields a linked-list stack has and how an empty stack is represented
  • Why the top of the stack is the head of the list, not the end
  • How create and isEmpty are written in C, Java and Python
5 minTime O(1)Memory O(1)C · Java · Python

1Idea

The structure has a single field: . It is a to the first node of the list; it is exactly the from the linked-list lessons, only renamed. When the stack is empty, top is . There is no items array and no capacity as in the array version.

Why is the top the head of the list? In a stack all the work happens at one end: adds at that end and removes from it. At the head both take : inserting at the head and deleting from the head touch only the first node.

If we put the top at the end of the list, adding would be quick with a tail pointer, but removing would not. To delete the last node you need the node before it, and in a singly linked list the only way to find it is to from the start. That is why deleting from the end is .

A linked-list stack has no isFull. The stack can only fail to grow when memory runs out, and finds that out by checking the result of malloc.

2Step by step

The drawing first shows an empty stack, then a stack after 10, 20 and 30 were added in that order. At each step the matching line of code lights up.

30?0x2c1020?0x1a9010?0x1a40top = NULL
  1. create writes into top. There are no nodes yet; this is the empty stack.
  2. isEmpty checks whether top is NULL. Right now it is, so the result is true.
  3. The state after three calls. 30, added last, is at the head of the list and top points to it.
  4. 30 is on top, and 10, added first, is at the bottom, the end of the list. The next push and pop will work only at the end where 30 is.
  5. isEmpty now returns false, because top points to a node.

struct Node {    int data;    struct Node* next;}; struct Stack {    struct Node* top;  // the top node}; void create(struct Stack* s) {    s->top = NULL;  // empty stack} bool isEmpty(struct Stack* s) {    return s->top == NULL;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} class LinkedStack {    Node top = null;  // the top node, null when empty     boolean isEmpty() {        return top == null;    }}
class Node:    def __init__(self, data):        self.data = data        self.next = None class LinkedStack:    def __init__(self):        self.top = None  # the top node, None when empty     def is_empty(self):        return self.top is None

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

3Complexity

Time
O(1)

Each function does a single assignment or comparison.

Memory
O(1)

An empty stack takes only the space of the top pointer.

Compare: an array stack reserves room for its full capacity up front. A linked-list stack allocates room node by node as elements arrive.

4Common mistake

A common mistake in C is using the stack without giving top a starting value:

struct Stack s;if (isEmpty(&s)) { ... }  // s.top is undefined

The fields of a local variable do not become NULL on their own; they hold some random address. isEmpty gives a wrong answer and the first tries to read from that address. Always call create(&s) before using the stack.

5Try it

If the top of a linked-list stack were at the end of the list, which operation would be O(n)?

Show the answer

The answer is B. In a singly linked list you cannot step back from a node. To remove the last node, the node before it is found by walking from the start. With the top at the head this problem does not exist.

How do you tell that a linked-list stack is empty?

Show the answer

The answer is B. In the linked-list version top is a pointer, not an index. When there is no node to point to, it is NULL. -1 marks an empty stack in the array version.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.