Professional Documents
Culture Documents
Week 03
Linked Lists / Slide 2
List Overview
Linked lists
Abstract data type (ADT)
Basic operations of linked lists
Insert, find, delete, print, etc.
Variations of linked lists
Circular linked lists
Doubly linked lists
Linked Lists / Slide 3
Linked Lists
A B C D
Head
A linked list is a series of connected nodes
Each node contains at least
A piece of data (any type)
Pointer to the next node in the list
Head: pointer to the first node node
The last node points to NULL A
data pointer
Linked Lists / Slide 4
Linked List
Tail Node: Points to the last element of the list
In case of only one element in the list the
TAIL and HEAD will both point towards the
same node.
Linked Lists / Slide 5
class Node {
public:
int data; // data
Node* next; // pointer to next
};
Linked Lists / Slide 6
Finding a node
int FindNode(double x)
Search for a node with the value equal to x in the list.
If such a node is found, return its position. Otherwise, return
0.
Node* List::FindNode(double x) {
Node* currNode = head;
while (currNode->data != x) {
currNode = currNode->next;
}
return currNode;
}
Linked Lists / Slide 17
Deleting a node
We delete any node of a linked list by connecting
the predecessor node of the node to be deleted by the
successor node of the same node.
For example, if we have a linked list a → b → c, then to delete
the node ‘b’, we will connect ‘a’ to ‘c’ i.e., a → c.
But this will make the node ‘b’ inaccessible and this type of
inaccessible nodes are called garbage and we need to clean this
garbage.
We do this cleaning by the use of ‘delete’ operator.
Linked Lists / Slide 18
Deleting a Node
Linked Lists / Slide 20
List::~List(void) {
Node* currNode = head, *nextNode = NULL;
while (currNode != NULL)
{
nextNode = currNode->next;
// destroy the current node
delete currNode;
currNode = nextNode;
}
}
Linked Lists / Slide 22
A B C
Head
A B C
Head
Linked Lists / Slide 26