Lecture 3: Linked List
A linked list is a chain of heap-allocated nodes, each holding data and a pointer to the next node. Every operation is pointer surgery, so the order of your assignments matters: relink the new node first, then the old one, or you lose the rest of the list.
Previous: Lecture 2 - Object Oriented Data Types · Next: Lecture 4 - Stack
Sections 1 to 7 follow the slides. Section 8 comes from the course practice sheet (questions 11 to 15). The slides write NULL; these notes write nullptr, which means the same thing here.
1. The idea
Think of children’s pop beads: you connect them into a chain, and you can move beads around and reconnect the chain. A linked list does the same with dynamically allocated structures joined by pointers.
flowchart LR
head["head"] --> A["hat | 2"] --> B["top | 3"] --> N["nullptr"]
- The first node is pointed to by
head. - Each node has a data element and a
nextpointer to the following node. - The last node’s
nextisnullptr. - A cursor points to the current node. It can only move forward (
cursor = cursor->next), which is how you traverse the list.
An array is one contiguous block, so a[i] is instant but growing means allocate, copy, delete (Lecture 2). A list grows one node at a time and inserting or deleting in the middle moves no data, but you must walk from head to reach a position.
2. Defining a node
Suppose each node holds a dictionary word and how many times it occurs:
struct elType { // the data element
std::string word;
int count;
};
struct node { // the node
elType e;
node* next; // address of the next node
};
node *p, *q; // pointers to nodes
Through a node* you reach p->e.word, p->e.count and p->next.
Allocate, fill, connect
p = new node; // two nodes on the heap
q = new node;
elType el1{"hat", 2}, el2{"top", 3};
p->e = el1;
q->e = el2;
p->next = q; // hat -> top
q->next = nullptr; // top is the last node
nextnew node leaves next uninitialized (the slide shows it as ?). A node you forget to link holds garbage, and walking into it is undefined behaviour. Give it a value (nullptr or the next node) immediately.
3. The five basic operations
flowchart LR
I1["insert at head"] --- I2["insert after a node"] --- I3["insert at end"] --- D1["delete head"] --- D2["delete non-head"]
Insert at the head
p = new node;
p->e = el;
p->next = head; // 1. new node points at the old first node
head = p; // 2. head now points at the new node
flowchart LR
head["head"] --> N["if | 4 (new)"] --> A["hat | 2"] --> B["top | 3"] --> X["nullptr"]
If you wrote head = p; first, the old head is overwritten and nothing points at hat any more: the whole old list is leaked. Link the new node to the list first, then move head.
This also works on an empty list: head is nullptr, so the new node’s next is nullptr and it becomes the only node.
Insert after a given node (the cursor)
p = new node;
p->e = el;
p->next = cursor->next; // 1. new node takes over cursor's successor
cursor->next = p; // 2. cursor now points at the new node
Same rule: steal the successor first, then redirect the cursor. Swapping the two lines makes p->next point at p itself and loses the tail of the list.
Insert at the end
p = new node;
p->e = el;
p->next = nullptr;
cursor->next = p; // cursor must be on the last node
To get cursor to the last node you walk until cursor->next == nullptr. Keeping a tail pointer avoids that walk (see section 8).
Delete the head
head points tohead is only a pointer variable; the node lives on the heap. You never delete head itself. You move it to the next node, and delete the old first node.
cursor = head;
head = head->next; // skip the first node
delete cursor; // then free it
Move head before delete; after delete you can no longer read ->next.
Delete a non-head node
You need the node’s predecessor, because that is the node whose next changes. With the predecessor in cursor:
node* q = cursor->next; // the node to delete
cursor->next = q->next; // unlink: bypass q
delete q;
A node only knows its successor. To remove node X you must change the pointer that points at X, and the only way to find it is to have kept the previous node. That is exactly why the slides track a prev pointer.
4. Variants
| Variant | What changes | Key fact |
|---|---|---|
| Circular | the last node points back to the first | tail->next == head; there is no nullptr, so traversal stops when you return to the start |
| Doubly linked | each node has next and back (also called prev) |
move both ways: cursor = cursor->next; / cursor = cursor->back; |
| Circular doubly linked | both of the above | head->back == tail and tail->next == head |
| 2-D list | nodes carry links in two dimensions | a grid of linked nodes (shown only as a diagram in the slides) |
flowchart LR
A["A"] <--> B["B"] <--> C["C"] <--> D["D"]
D <--> A
while (p != nullptr) never ends on a circular list. Use a do { ... p = p->next; } while (p != head); loop instead.
Doubly linked lists cost more per node (an extra pointer) and every insert or delete updates more links, but deleting a node no longer needs a separate prev: the node itself knows its predecessor.
5. The List ADT
The slides build an ordered linked list class List as a template, so the key and data types are chosen by the user. A node holds a key, a data field and next. Searching is by key, and the list is kept ascending on the key.
Three private pointers describe the state:
| Pointer | Meaning |
|---|---|
head |
the first node |
cursor |
the current node (empty = nullptr) |
prev |
the node just before cursor (needed for deletion and insertBefore) |
flowchart LR
head["head"] --> N1["key | data"] --> N2["key | data"] --> N3["key | data"] --> Z["nullptr"]
prev["prev"] -.-> N1
cursor["cursor"] -.-> N2
Operations and what happens to the current position
| Group | Operation | Effect |
|---|---|---|
| Setup / checks | List() |
empty list: head, cursor, prev all nullptr |
listIsEmpty() |
head == nullptr |
|
curIsEmpty() |
no current node | |
toFirst() |
cursor = head; stays empty on an empty list |
|
atFirst() |
true if current is first (or both are empty) | |
| Traversal | advance() |
prev = cursor; cursor = cursor->next; current must be non-empty |
toEnd() |
current becomes the tail | |
atEnd() |
true if current is the tail (or both empty) | |
listSize() |
count the nodes | |
| Data | retrieveData(d) / updateData(d) |
read / overwrite the current node’s data |
| Insert | insertFirst(k, d) |
new node at head; becomes current |
insertAfter(k, d) |
after current; current unchanged (slides) | |
insertBefore(k, d) |
before current; current becomes the new node | |
insertEnd(k, d) |
at the end; current becomes the new node | |
orderInsert(k, d) |
keeps keys ascending | |
| Delete | deleteNode() |
delete current; current becomes the next node (empty if it was last) |
deleteFirst() |
delete head; current becomes the next node (empty if it was the only node) | |
deleteEnd() |
delete last; current becomes empty | |
makeListEmpty() |
free every node | |
| Other | search(k) |
found: cursor on that node, true. Not found: current becomes empty, false |
traverse() |
print every key and data |
The slides say insertAfter does not change the current position. The practice sheet (question 14) states “insertion moves current to the new node”. When you answer sheet-style trace questions, use the rules the question states. See section 8.
Class declaration (shape)
template <class keyType, class dataType>
class List {
public:
List(); // empty list
~List(); // calls makeListEmpty()
bool listIsEmpty() const;
bool curIsEmpty() const;
void toFirst();
bool atFirst() const;
void advance();
void toEnd();
bool atEnd() const;
int listSize() const;
void updateData(const dataType&);
void retrieveData(dataType&) const;
void insertFirst (const keyType&, const dataType&);
void insertAfter (const keyType&, const dataType&);
void insertBefore(const keyType&, const dataType&);
void insertEnd (const keyType&, const dataType&);
void deleteNode();
void deleteFirst();
void deleteEnd();
void makeListEmpty();
bool search(const keyType&);
void orderInsert(const keyType&, const dataType&);
void traverse();
private:
class node { // hidden from the user
public:
keyType key;
dataType data;
node* next;
};
typedef node* NodePointer;
NodePointer head, cursor, prev;
};
The node class lives in the private part: users of the list never see nodes, only the operations. That is the ADT idea from Lecture 2 - Object Oriented Data Types applied to a real structure. Because it is a template class, the implementation is #included at the end of the header.
6. Implementation walkthrough
template <class keyType, class dataType>
List<keyType, dataType>::List() {
head = NULL; cursor = NULL; prev = NULL;
}
template <class keyType, class dataType>
List<keyType, dataType>::~List() {
makeListEmpty(); // free every node
}
template <class keyType, class dataType>
bool List<keyType, dataType>::listIsEmpty() const {
return head == NULL;
}
template <class keyType, class dataType>
void List<keyType, dataType>::toFirst() {
cursor = head; prev = NULL; // empty list: cursor stays empty
}
template <class keyType, class dataType>
void List<keyType, dataType>::advance() {
prev = cursor; // remember where we were
cursor = cursor->next;
}
template <class keyType, class dataType>
void List<keyType, dataType>::toEnd() {
toFirst();
if (!listIsEmpty())
while (cursor->next != NULL)
advance(); // stop ON the last node
}
template <class keyType, class dataType>
int List<keyType, dataType>::listSize() const {
NodePointer q = head;
int count = 0;
while (q != NULL) {
count++;
q = q->next;
}
return count;
}
template <class keyType, class dataType>
void List<keyType, dataType>::insertFirst(const keyType& k, const dataType& d) {
NodePointer pnew = new node;
pnew->key = k; pnew->data = d;
pnew->next = head; // link first ...
head = pnew; // ... then move head
cursor = head; // the new node becomes current
prev = NULL;
}
Things to notice:
toEndstops atcursor->next == NULLsocursorfinishes on the last node (not past it), andprevfollows one step behind throughadvance.listSizeuses a local pointerq, so counting doesn’t disturbcursororprev. It isconstbecause it changes nothing.- The destructor delegates to
makeListEmpty. Without it, every node leaks when the list goes out of scope.
Check the remaining operations, and the array-based implementation of a linked list (next “pointers” stored as array indices).
7. Pitfalls
Debug this
void insertAfterCursor(node* cursor, node* p) {
cursor->next = p;
p->next = cursor->next; // BUG
}
cursor->next was already overwritten with p, so p->next = p: the node points at itself and the rest of the list is lost. Fix: do p->next = cursor->next; first, then cursor->next = p;.
void deleteHead() {
delete head;
head = head->next; // BUG: use after delete
}
Fix: save head, move head forward, then delete the saved node.
- Wrong assignment order, which loses part of the list.
- Using a node after
delete. - Forgetting to update
head(inserting or deleting at the front) ortail(at the end). - Dereferencing
nullptr: always testcursor != nullptrbeforecursor->next. - Leaking nodes: free every node in the destructor.
8. Practice sheet: head, tail and current
These problems use a singly linked list with head, tail and sometimes current. Keeping a tail makes appending O(1), but it is one more pointer you must keep correct.
Q11: insert and delete, tracking the list pointers
Start: head → A(4) → B(8) → C(12) → nullptr, tail → C.
| Step | Link changes | List afterwards |
|---|---|---|
| insert D(6) after A | D.next = B, then A.next = D |
A → D → B → C |
| delete B | D.next = C, then free B |
A → D → C |
| insert E(2) at head | E.next = A, head = E |
E → A → D → C |
| append F(14) | F.next = nullptr, C.next = F, tail = F |
E → A → D → C → F |
Only the append changes tail, and only the head insert changes head.
Q12: delete the first match
bool removeFirst(int key) {
Node* prev = nullptr;
Node* node = head;
while (node && node->key != key) { // find it, remembering the predecessor
prev = node;
node = node->next;
}
if (!node) return false; // not found
if (prev) prev->next = node->next; // middle or tail
else head = node->next; // it was the head
if (node == tail) tail = prev; // removed the last node
delete node;
return true;
}
Trace on 7 → 3 → 7:
| Call | Result | List | head / tail |
|---|---|---|---|
removeFirst(7) |
true | 3 → 7 | 3 / 7 |
removeFirst(7) |
true | 3 | 3 / 3 |
removeFirst(3) |
true | empty | nullptr / nullptr |
The last call works because removing the only node makes head = node->next = nullptr and tail = prev = nullptr.
Q13: ordered insert with duplicates
void orderedInsert(int key) {
Node* prev = nullptr;
Node* next = head;
while (next && next->key <= key) { // <= : go PAST equal keys
prev = next;
next = next->next;
}
Node* node = new Node{key, next};
if (prev) prev->next = node;
else head = node;
if (!next) tail = node; // inserted at the end
}
Starting from 4 → 9a → 9b → 15:
- insert
2:2 → 4 → 9a → 9b → 15(new head) - insert
9c:2 → 4 → 9a → 9b → 9c → 15(after the existing 9s) - insert
20:2 → 4 → 9a → 9b → 9c → 15 → 20(new tail)
<= makes it stableWith < the new 9 would land before the existing 9s. <= places it after them, so equal keys stay in insertion order.
Q14: following current
List 10 → 20 → 30, head = 10, tail = 30, current = 20. The sheet’s rules: insertion moves current to the new node, advance() moves it one forward, deleteEnd() clears it, toEnd() selects the tail, and deleteHead() clears it only if it selected the deleted node.
| Call | List | (head, tail, current) |
|---|---|---|
insertAfter(25) |
10 → 20 → 25 → 30 | (10, 30, 25) |
advance() |
10 → 20 → 25 → 30 | (10, 30, 30) |
deleteEnd() |
10 → 20 → 25 | (10, 25, nullptr) |
toEnd() |
10 → 20 → 25 | (10, 25, 25) |
deleteHead() |
20 → 25 | (20, 25, 25) |
deleteHead() leaves current alone because it pointed at 25, not at the deleted 10.
Q15: circular doubly linked list
A ⇄ B ⇄ C ⇄ D, circular, head = A.
Delete A, new head B:
D->next = B;
B->prev = D;
head = B;
delete A;
Insert X between D and B (head stays B):
X->prev = D;
X->next = B;
D->next = X;
B->prev = X;
Forward from head: B → C → D → X → B. Backward from head: B → X → D → C → B.
Inserting between two neighbours in a doubly linked list always changes four links: two on the new node, and one on each neighbour. Set the new node’s two links first (they read the neighbours), then fix the neighbours.
Quick self-test
Which two lines insert p after cursor, and in what order?
p->next = cursor->next; then cursor->next = p;. Reversed, p points at itself.
Why does deleting a non-head node need its predecessor?
The predecessor’s next is the pointer that must skip the node, and a singly linked node can’t find its predecessor.
What does toEnd() leave cursor pointing at?
The last node (it stops when cursor->next == NULL).
What makes orderedInsert keep duplicates in arrival order?
The loop condition next->key <= key, so a new equal key goes after the existing ones.
When does removeFirst have to update tail?
When the removed node is the tail (node == tail), including the one-node case.
How do you stop a traversal of a circular list?
When the pointer returns to head; there is no nullptr.
Cheat sheet
- Node = data +
next. Last node’snextisnullptr.headpoints at the first node. new node→ fill data → setnext→ link in.- Insert after cursor:
p->next = cursor->next;thencursor->next = p;. - Insert at head:
p->next = head;thenhead = p;. - Delete head: move
headfirst, thendeletethe old one. - Delete a middle node: need the predecessor;
prev->next = node->next;thendelete node;. - Updating
head/tail: head insert or delete changeshead; append or deleting the last node changestail; one-node list changes both. - Circular:
tail->next == head, loop until you return tohead. - Doubly linked: inserting between neighbours changes four links.
Listclass: privatehead,cursor,prev; destructor callsmakeListEmpty().- Use a local pointer to traverse so you don’t disturb
cursor. - Ordered insert with
<=is stable for duplicate keys.