Professional Documents
Culture Documents
Linked Lists
Memory Allocation
There are essentially two types of memory allocation
Static – Done by the compiler automatically (implicitly).
Global variables or objects -- memory is allocated at the start of
the program, and freed when program exits; alive throughout
program execution
Can be access anywhere in the program.
Local variables (inside a routine) – memory is allocated when the
routine starts and freed when the routine returns.
A local variable cannot be accessed from another routine.
Allocation and free are done implicitly.
No need to explicitly manage memory is nice (easy to work with),
but has limitations!
Using static allocation, the array size must be fixed.
Consider the grade roster for the class? What is the number of people in the
class?
Cont..
There are essentially two types of memory
allocation
Wouldn’t it be nice to be able to have an array
whose size can be adjusted depending on needs.
Dynamic memory allocation deals with this situation.
4-
11
Singly Linked List
head pointer "defines" the linked list
head (note that it is not a node)
4-
12
Linked List
Note: we will hereafter refer to a singly linked list just as a
“linked list”
4-
13
Linked List Operations
We will now examine linked list operations:
Add an item to the linked list
◦ We have 3 situations to consider:
insert a node at the front
insert a node in the middle
insert a node at the end
Delete an item from the linked list
◦ We have 3 situations to consider:
delete the node at the front
delete an interior node
delete the last node
4-
14
Inserting a Node at the Front
node
node points to the new node to be
inserted, front points to the first node
of the linked list
front
node
1. Make the new node point to the
first node (i.e. the node that front
points to)
front
4-
15
node
2. Make front point to the new node
(i.e the node that node points to)
front
4-
16
Inserting a Node in the Middle
node
Let's insert the new node after the third
node in the linked list
front
current
4-
17
2. Make the new node point to the node
after the insertion point (i.e. the node node
pointed to by the node that current
points to)
front
current
node
3. Make the node pointed to by current
point to the new node
front
X
current
4-
18
Deleting the First Node
front points to the first node in the linked list,
which points to the second node
front
front
X
4-
19
Deleting
front
an Interior Node
previous current
front
previous current
previous current
4-
21
Doubly Linked Lists
In a doubly linked list, each node has two
links:
◦ A reference to the next node in the list
◦ A reference to the previous node in the list
What is the “previous” reference of the first node in
the list?
4-
22
Doubly Linked List
head tail
. .
4-
23