06 DS Linked Lists 1
06 DS Linked Lists 1
Linked Lists
(Part 1)
Topic Structure
• Node
• Head
• Traversal
b e a d a
0 1 2 3 4 …
CT077-3-2-DSTR Data Structures 5
Introduction
Structure of a node
Linked list
CT077-3-2-DSTR Data Structures 8
Linked Lists
• Example: a list containing two elements (45 and 65)
– supposing the first node is at memory location
1200, and the second node is at memory
location 1575, linked list will look like this
Value
current 2000
current->info 17
current->link 2800
current->link->info 92
• current = current->link;
– Copies value of current->link (2800)
into current
Value
current 2800
current->info 92
current->link 1500
current->link->info 63
CT077-3-2-DSTR Data Structures 14
Linked Lists: Some Properties
Value
head->link->link 1500
head->link->link->info 63
head->link->link->link 3600
head->link->link->link->info 45
current>link->link 3600
current->link->link->info 45
current>link->link->link 0 (that is, NULL)
current>link->link->link->info Does not exist gives runtime error
while(current != NULL){
size++;
current = current->link;
}
LinkedList();
int getSize();
...
};
CT077-3-2-DSTR Data Structures 19
Size of a LinkedList
• Create a size field (data member) encapsulated in the
LinkedList data structure (initialized to zero in constructor)
• Update the field upon insertion and deletion (+1 or -1)
class LinkedList {
public: Improve getSize() ?
NodeType* head;
This is a simple example
int size; of how a data structure
int getSize(){ and an algorithm
X
int size = 0; cooperate to implement
NodeType * current = head; efficient solutions.
while(current != NULL){
size++; We traded off extra small
current = current->link; memory (not necessarily
} always small) to gain
return size; speed in calculating the
} size of the linked list.
};
CT077-3-2-DSTR Data Structures 20
Inserting a New Element
list.insertAtBeginning(5);
LinkedList l1;
LinkedList l2;
l1.insertAtBeginning(5);
l1.insertAtBeginning(9);
l1.insertAtBeginning(3);
cout << l1.getSize() << endl;
l2.insertAtBeginning(9);
l2.insertAtBeginning(7);
cout << l2.getSize() << endl;
}
size = 0;
}
list.insertAtBeginning(5);
list.insertAtEnd(9);
list.insertAtBeginning(3);
cout << list.getSize() << endl;
list.print();
list.insertAtEnd(11);
cout << list.getSize() << endl;
list.print();
}
CT077-3-2-DSTR Data Structures 27
Summary of Main Teaching