Data Structures: Linked Lists (Part 3)
Data Structures: Linked Lists (Part 3)
Data Structures: Linked Lists (Part 3)
Linked Lists
(Part 3)
Topic Structure
• Tail
• Reverse traversal
• Doubly linked list
• Circular linked list
X X
lastNode
newNode newNode
X
5
newNode
if(head == NULL)
tail = NULL;
}
}
beforeLast
class LinkedList {
void printReverse(){
printRecursive(head);
}
void printRecursive(NodeType * current){
if(current != NULL) {//stop recursion if we reach list end
printRecursive(current->link); //print remaining items first
cout << current->info << " "; //then print current item
}
}
};
CT077-3-2-DSTR Linked List (Part 3) Slides 14 of 32
p
r
p
i
rn How is Recursion Executed?
it
n
R
te
R
c
e
u
cr
void printRecursive(NodeType
p * current){
u
s
if(current
ri != NULL){
ri nt
printRecursive(current->link);
sv void printReverse(){ cout s << current->info << " ";
ie printRecursive(head); 6
3
7
} 5,
4,
6,
v }
e } r
o
et
f prints 45, done. return to caller
o u
fn r
n
o
n to
d
u c
e
l al
l7 le recursion ends,
4
6
3
r execution returns to
5
4
6
n
, caller
o
d
c
e
a
,l
l
n
s
o
…
CT077-3-2-DSTR Linked List (Part 3) Slides 15 of 32
Doubly Linked Lists
X
X
4
newNode
X
X
4 newNode
beforeThis newNode
CT077-3-2-DSTR Linked List (Part 3) Slides 19 of 32
Inserting at Arbitrary Index
//code continues
newNode->next = beforeThis;
newNode->prev = beforeThis->prev;
beforeThis->prev = newNode;
newNode->prev->next = newNode;
size++;
newNode beforeThis
beforeThis
newNode
void print(){
if(tail != NULL){
NodeType<T> * current = tail->link;
do{
cout << current->info << " ";
current = current->link;
}while (current != tail->link);
cout << endl;
}
}
};
CT077-3-2-DSTR
current
Linked List (Part 3) Slides 26 of 32
Circular Linked List Operations
X
4
newNode
CT077-3-2-DSTR Linked List (Part 3) Slides 27 of 32
Array or Linked List?
• Finally, should we always use linked lists?
• Decision depends on what operations will be used
most frequently, and which factors (speed/memory)
are more critical. Following are some hints:
– Number of elements is known: use array
– Dynamic addition and expansion: linked list
– Deletion at any position: linked list
– Need lots of random access: use array
– Searching and items are unsorted: both same
– Searching and items are sorted: array (binary search)
– Sorting using bubble sort: both same
– Sorting using other methods: depends on the method
CT077-3-2-DSTR Linked List (Part 3) Slides 28 of 32
Summary of Main Teaching
• Stack
– Applications
– Operations
– Implementation