Linked Lists
Linked Lists
Traversal
Insertion
Deletion
LB
42 98 12 6
heap
head stack
LB
12
LB
Procedure Traverse
(current isoftype in Ptr toa Node)
// Precon: Pass in pointer to a list
// Purpose: Print each data item
// Postcon: No changes to list
if(current <> NIL) then
print(current^.data)
Traverse(current^.next)
endif
endprocedure // Traverse
LB
42 98 12 6
heap
head stack
LB
Questions?
Insertion Into Linked Lists
Node Definition
head 48 17 142 //
head 93
head 48 17 142
Don’t Worry!
Inserting to the Middle
head 17 48 142
93 //142 //
• To front
– No recursion needed
• To end
– Get to the end, then add node
• In order (in middle)
– To maintain sorted property
Inserting at the Front of a
Linked List
Inserting to the Front of a Linked List
4 17 42
2
head 48 17 142 53
current R new_data 53
current R new_data 53
current R new_data 53
current R new_data 53
Inserting in Order into a
Linked List
Inserting In Order into a Linked List
Head 13 18 23
19
6 4 17 42
6 4 17 42
4 17 42
4 17 42
procedure DeleteFront
(current iot in/out ptr toa Node)
// deletes the first node in the list
if (current <> nil) then
current <- current^.next
endif
endprocedure
Deleting from a Linked List
6 4 17 42
.
.
Delete(head, 4)
.
.
head
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 4 17 42
6 17 42
6 17 42
6 17 42
.
.
Delete(head, 4)
.
.
Linked List Deletion
(All Occurrences)
Deleting All Occurrences
6 4 17 4
.
.
Delete(head, 4)
.
.
head
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 4 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17 4
6 17
6 17
6 17
6 17
6 17
6 17
6 17
6 17
.
.
Delete(head, 4)
.
.
Summary
• Deletion involves:
– Getting to the correct position
– Moving a pointer so nothing points to
the element to be deleted