2. Doubly linked lists
A doubly linked list is a list that can be traversed both from
left to right and from right to left
It requires to store two head pointers:
The first one points to the first element in the list
The second one points to the last element in the list
first
last
3. Linked lists vs. Doubly linked lists
Linked lists
Simple implementation
Require less memory
Doubly linked lists
More complex implementation
Require more memory
Accessing elements is easier, since accessing from the “head” (i.e.,
leftmost element) costs as much as accessing from the “tail” (i.e.,
rightmost element)
Worst case: accessing the middle element (it requires to go
through half list, both from left and from right)
5. Node definition
Each node contains:
The data
A pointer to the previous element (left-side)
A pointer to the next element (right-side)
previousPtr data nextPtr
6. Creating a doubly linked list
We are going to create a doubly linked list by hand:
first second last
7. second last
Creating a doubly linked list
We are going to create a doubly linked list by hand:
first
8. second last
Creating a doubly linked list
We are going to create a doubly linked list by hand:
first
9. Print the list starting from the head
Strategy
Start from the head (i.e., the leftmost element)
Use the nextPtr pointers to go through the list, from left to right
10. Print the list starting from the tail
Strategy
Start from the tail (i.e., the rightmost element)
Use the previousPtr pointers to go through the list, from right to
left