CSC 288 · Structured Programming
Our notes
2 min readWhy dynamic data
Arrays have a fixed size chosen when the program is written. Dynamic data structures grow and shrink while the program runs: the program asks for memory as it needs it.
Pointers in Pascal
type
NodePtr = ^Node;
Node = record
data: integer;
next: NodePtr
end;
var head, p: NodePtr;
- new(p) creates a node and makes p point to it.
- p^.data is the data in the node p points to.
- nil means "points to nothing".
- dispose(p) returns the node's memory.
Building a list (insert at the front)
head := nil;
for i := 1 to 3 do
begin
new(p);
p^.data := i * 10;
p^.next := head;
head := p
end;
The list is now 30 → 20 → 10 → nil (each new node goes in front).
Walking a list
p := head;
while p <> nil do
begin
write(p^.data, ' ');
p := p^.next
end;
Output: 30 20 10
Inserting in order
To keep the list sorted, find the node after which the new one belongs (the last node with data smaller than the new value), then link: new^.next := prev^.next; prev^.next := new. Inserting at the head is a special case.
Deleting a node
Find the node before it (prev), unlink it with prev^.next := target^.next, then dispose(target).
Lists against arrays
| Array | Linked list | |
|---|---|---|
| Size | fixed | grows as needed |
| Reach element k | direct, one step | walk k nodes |
| Insert or delete in the middle | move many elements | change two pointers |
| Extra memory | none | one pointer per node |
Other dynamic structures
Stacks (push and pop at the head), queues (add at the tail, remove at the head), doubly linked lists, and trees (next topic) are all built the same way.
Exams usually ask
- Explain pointers, new, dispose and nil.
- Write code to build, traverse, insert into and delete from a linked list.
- Compare arrays and linked lists.
Common mistake
Losing the rest of the list when inserting: setting prev^.next := new before new^.next := prev^.next cuts the list off. Link the new node to the rest first.
Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.
No reading links here yet
Our team adds free books, videos and practice for each topic, and opens every link before it goes up.