Dynamic Data Structures - Linked Lists
Transcriber’s note: Each row in the Value|Pointer/Link tables represents a node. Despite the fact that the link/pointer takes you to the “value” column, in reality it is taking you to the node “row”, it’s not just a pointer to the value.
Dynamic Data Structures
- Basic types (e.g. int, char, bool, …), and arrays of these store a fixed amount of data.
- We want implementations of ADTs like stacks + queues to grow & shrink (their memory use) as needed.
- e.g. like Vector, Array-something? (can’t read), String classes
Basic Idea:
Store data in a collection of (simple) objects. add/delete these as needed; link them all together to make the main object.
Linked Lists
- A sequence of simple objects (nodes): each storing one datum (plus a link…) linked together in a chain
- E.g., to store the list <3, 5, 7>:
Datum | Link |
---|---|
3 | link |
5 | link |
7 | link to nowhere |
- These objects have no names, (in contrast to declared values)
- we access them by following links
- in Java, references (implemented as pointers)
- in C++, pointers
- we access them by following links
Need one named place to start like so:
A normal variable of type “pointer to a node”: First
Data | Link |
---|---|
3 | pointer |
5 | pointer |
7 | null pointer |
Implementing a Stack with a Linked List (By example)
Code to run, followed by the current stack.
stack s;
node
s.push(3)
Data | Pointer |
---|---|
3 | null pointer |
etc…
…
s.push(5)
Data | Pointer |
---|---|
5 | pointer |
8 | pointer |
… | … (pointer) |
3 | null pointer |
s.push(7)
Value | Pointer |
7 | pointer |
5 | pointer |
8 | pointer |
… | … |
To perform the push(7):
- Make a new node to store the 7
- modify links to insert it correctly
Original:
Data | Pointer |
---|---|
5 | pointer |
8 | … |
After operation:
front now points at node with value 7; node with value 7’s pointer now points to the old front
Value | Pointer |
---|---|
7 | pointer |
5 | pointer |
8 | … |
s.pop()
Value | Pointer |
---|---|
5 | pointer |
8 | … |
How to perform the pop():
- Change the “top” link
- Return the old top node
Linked list after running operation (note that two links go to the same node):
top now points to second row
Value | Pointer |
---|---|
7 (return this value) | pointer |
5 | pointer |
8 | … |
- Caveat 1: don’t lose the old top value
- Caveat 2: don’t ignore the old top node (it still consumes space)
“Improved” pop():
- Store the old top value in “temp”
- make top link to the new top node
- free the space for the old top node
- return temp
The List Class (A doubly-linked list implementation of a list)
See list.cpp
<…5,6,7,…> in a double linked list:
Prev | Value | Next |
---|---|---|
… | 5 | next |
prev | 6 | next |
prev | 7 | … |