Data Structures and Algorithms - Linked Lists
Data Structures and Algorithms - Linked Lists
Algorithms
CSC7202
but
Must specify size at construction time
If you construct an array with space for twice your
estimate, Tomorrow youll need n+1
Any more flexible system?
Linked Lists
Definition: a list of items, called nodes, in which the order of
the nodes is determined by the address, called the link, stored
in each node.
Data Next
object
Linked Lists
The address of the first node in the list is stored in a separate
location, called the head or first which should always point to
the first node
PTR
10 20 30 40
10 20 30 40 50
Me Her You Them
START Data Link
PTR
10 20 30 40
10 20 30 40 50
Me Her You Them
START Data Link
PTR
Linked List: Traversal
Let START be a pointer to a linked list in memory.
Write an algorithm to print the contents of each
node of the list
Algorithm
1. set PTR = START
2. while PTR NULL, repeat step 3 and 4
3. print PTR->DATA
4. set PTR = PTR -> LINK
5. stop
Linked List: Searching
Him Us Me You
START
PTR
Him Us Me You
START
PTR
Him Us Me You
START
PTR
Linked List: Searching
Let START be a pointer to a linked list in memory. Write an algorithm that
finds the location LOC of the node where ITEM first appears in the list, or
sets LOC=NULL if search is unsuccessful.
Algorithm
1. set PTR = START
2. repeat step 3 while PTR NULL
3. if ITEM == PTR -> DATA, then
4. set LOC = PTR, and Exit
5. else
6. set PTR = PTR -> LINK
7. set LOC = NULL /*search unsuccessful */
8. Stop
Linked List: Insertion
Node A Node B
1000 2000 3000 4000 5000
START
Node A Node B
START
3500
Node N
PTR
Linked List: Insertion
Let START be a pointer to a linked list in memory with
successive nodes A and B. Write an algorithm to insert node
N between nodes A and B.
Algorithm
1. Set PTR = START
2. Repeat step 3 while PTR NULL
3. If PTR == A, then
4. Set N->LINK = PTR -> LINK (or = B)
5. Set PTR->LINK = N
6. exit
7. else
8. Set PTR=PTR->LINK
9. If PTR == NULL insertion unsuccessful
10. Stop
Linked List: Deletion
1000 2000
.. 3000 3500 4000 5000
3500
Algorithm
1. Set PTR=START and TEMP = START
2. Repeat step 3 while PTR NULL
3. If PTR->DATA == ITEM, then
4. Set TEMP->LINK = PTR -> LINK, exit
5. else
6. TEMP = PTR
7. PTR = PTR -> LINK
8. Stop
Linked List Performance Summary
Pros
Insertion and Deletion is easy
Dynamic Size
Cons
Searching is (worst case) slow
NEXT: Stacks