5-LinkedLists and Iterators
5-LinkedLists and Iterators
These slides has been extracted, modified and updated from original slides of :
• Data Structures and Algorithms in Java, 5th edition. John Wiley& Sons, 2010. ISBN 978-0-470-38326-1.
• Dr. Hanna’s slides (http://aimanhanna.com/concordia/comp352/index.htm)
❑ Iterators
A B C D
4. Update head to
point to new node
Linked Lists & Iterators 5
Removing at the Head
1. Update head to
point to next node
in the list
2. Allow garbage
collector to reclaim
the former first
node
❑ There is no constant-
time way to update the
tail to point to the
previous node
nodes
t
elements
Linked Lists & Iterators 9
Queue as a Linked List (Review Section 5.2.3)
f
elements
Linked Lists & Iterators 10
Doubly Linked List
❑ A doubly linked list provides a natural
implementation of the Node List ADT prev next
❑ Nodes implement Position and store:
◼ element
◼ link to the previous node
◼ link to the next node elem node
❑ Special sentinel/dummy trailer and header nodes
(simplify implementation)
header nodes/positions trailer
elements
Linked Lists & Iterators 11
Insertion
❑ We visualize operation addAfter(p, X), which returns position q
p
A B C
p
A B q C
X
p q
A B X C
Linked Lists & Iterators 12
Insertion Algorithm
Algorithm addAfter(p,e):
Create a new node v
v.setElement(e)
v.setPrev(p) {link v to its predecessor}
v.setNext(p.getNext()) {link v to its successor}
(p.getNext()).setPrev(v) {link p’s old successor to v}
p.setNext(v) {link p to its new successor, v}
return v {the position for the element e}
A B C D
A B C p
A B C
Linked Lists & Iterators 14
Deletion Algorithm
Algorithm remove(p):
t = p.element {a temporary variable to hold the
return value}
(p.getPrev()).setNext(p.getNext()) {linking out p}
(p.getNext()).setPrev(p.getPrev())
p.setPrev(null) {invalidating the position p}
p.setNext(null)
return t