Week 8
Week 8
CSO102
WEEK-8 (DRAFT)
LINKED LIST:
Each node consists of two fields: one field has data, and in the
second field, the node has an address that keeps a reference to the
next node.
LINKED LIST: OPERATIONS
?
LINKED LIST: IMPLEMENTATION
struct Node {
int data;
struct Node* next;
};
LINKED LIST: TRAVERSAL
IMPLEMENTATION
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// This function prints contents of linked list starting
// from the given node
void printList(struct Node* n)
{
while (n != NULL) {
printf(" %d ", n->data);
n = n->next;
}
}
return 0;
}
LINKED LIST: TRAVERSAL
IMPLEMENTATION
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
head->data = 1; // assign data in first node
head->next = second; // Link first node with second
second->data = 2; // assign data to second node
second->next = third;
third->data = 3; // assign data to third node
third->next = NULL;
// Function call
printList(head);
return 0;
}
LINKED LIST: VARIATIONS
HowThe
do last node when
we know pointswe
tohave
the first nodetraversing
finished of the listThe last(Tip:
the list? nodecheck if the
poinHow
pointer of thedo we know
current nodewhen wetohave
is equal finished traversing the list?
the head.)
(Tip:How do we know when we have finished traversing the list?
(Tip: check if the pointer of the current node is equal to the head.)
check if the pointer of the current node is equal to the head.)
ts to the first node of the list
DOUBLY LINKED LIST
There are two NULL: at the first and last nodes in the list
Circular Doubly Linked List has properties of both doubly linked list
and circular linked list.
Two consecutive elements are linked or connected by the previous
and next pointer and the last node points to the first node by the next
pointer and also the first node points to the last node by the previous
pointer.
WHY LINKED LIST OVER ARRAY