Linked Lists and Memory Management
Linked Lists and Memory Management
This domain tests dynamic node structures, pointer rewiring, and the lifetime rules of heap memory.
Linked list basics
- A node holds
dataand anextpointer. The list is accessed throughhead; the last node'snextisnullptr. - Unlike arrays, nodes need not be contiguous; insertion/deletion at a known position is O(1), but search is O(n).
- Traversal:
for (Node *p = head; p != nullptr; p = p->next).
Dynamic memory
newallocates on the heap and returns an address;deletefrees one object,delete[]frees an array.- Every successful
newneeds exactly one matchingdelete; otherwise a memory leak occurs. - After
delete p, setp = nullptrto avoid a dangling pointer. - Deleting the same pointer twice is undefined behaviour.
Worked example
Insert 5 at the front: Node *n = new Node; n->data = 5; n->next = head; head = n;. Reasoning: the new node must point to the old first node before head is changed; reversing these two statements loses the rest of the list. For deletion of the head: Node *t = head; head = head->next; delete t;.
Traps
- Overwriting
headbefore saving the old head. - Forgetting to set the last node's
nexttonullptr, causing traversal to run into garbage. - Using
deleteinstead ofdelete[]for arrays. - Accessing a node after freeing it.
- Confusing a node with a pointer to a node in declarations.