SlideShare a Scribd company logo
LINKED LIST
LINKED LIST Definition:
• A linked list is a linear data structure where each element is a
separate object.
• Linked list elements are not stored at contiguous location;
the
elements are linked using pointers.
• LINKED LIST is a collection of data elements called nodes
where the linear order is given by means of pointer.
• Each node of a list is made up of two items - the data and
a reference to the next node.
• The last node has a reference to null.
Representation of a node:
Chandigarh Group of Colleges, Landran
Chandigarh Group of Colleges, Landran
Example of LINKED List:
Representation of Linear Linked
Chandigarh Group of Colleges, Landran
Example of linked list :
Chandigarh Group of Colleges, Landran
Types of Linked list:
• Linear or Singly linked list
• Circular Linked List
• Doubly Linked list
Chandigarh Group of Colleges, Landran
Singly or Linear linked list
VS
Circular
Linked
List:
CS 10001 : Programming and Data Stru
ctures
10
Lecture #05: © DSamanta
Types of Lists: Circular Linked List
Circular linked list
• The pointer from the last element in the list points back to
the first element.
A B C
head
11
Circular Linked List
• A circular linked list is basically a linear linked list that may be single- or
double-linked.
• The only difference is that there is no any NULL value terminating the list.
• In fact in the list every node points to the next node and last node points to the
first node, thus forming a circle. Since it forms a circle with no end to stop it is
called as circular linked list.
• In circular linked list there can be no starting or ending node, whole node can be
traversed from any node.
• In order to traverse the circular linked list, only once we need to traverse entire
list until the starting node is not traversed again.
• A circular linked list can be implemented using both singly linked list and
doubly linked list.
Chandigarh Group of Colleges, Landran
Single or Linear linked list
VS
Double Linked List:
13
Types of Lists: Double Linked List
Double linked list
• Pointers exist between adjacent nodes in both directions.
• The list can be traversed either forward or backward.
• Usually two pointers are maintained to keep track of the list, head and
tail.
A B C
head tail
Double Linked List
• Doubly linked list is a collection of nodes linked together in a sequential way.
• Doubly linked list is almost similar to singly linked list except it contains two
address or reference fields, where one of the address field contains reference of
the next node and other contains reference of the previous node.
• First and last node of a linked list contains a terminator generally a NULL
value, that determines the start and end of the list.
• Doubly linked list is sometimes also referred as bi-directional linked list since it
allows traversal of nodes in both direction.
• Since doubly linked list allows the traversal of nodes in both direction, we can
keep track of both first and last nodes.
Linked Lists in C
CS 10001 : Programming and Data Stru
ctures
16
Operations on single linked list
Lecture #05: © DSamanta
• Creating a Node
• Traversing a list
• Printing, finding minimum, etc.
• Insertion of a node into a list
• At front, end and anywhere, etc.
• Deletion of a node from a list
• At front, end and anywhere, etc.
CS 10001 : Programming and Data Stru
ctures
17
Lecture #05: © DSamanta
Defining a Node of a Linked List
Each structure of the list is called a node, and consists of two fields:
• Item (or) data
• Address of the next item in the list (or) pointer to the next node in the
list
struct node
{
int data; /* Data */
struct node *next; /* pointer*/
} ;
Data
next
node
Note:
Such structures which contain a member field pointing to the same structure type are
called self-referential structures.
How to define a node of a linked list?
18
newNode = (struct node *)malloc(sizeof(struct node));
newNode->data = data; //Links the data field of newNode with data
newNode->next = NULL; //Links the address field of newNode with NULL
temp->next = newNode; //Links previous node i.e. temp to the newNode
temp = temp->next;
head
100 NULL
If we need n number of nodes in the linked list:
• Allocate n newNodes, one by one.
• Read in the data for the newNodes.
• Modify the links of the newNodes so that the chain is formed.
It creates n number of nodes . For e.g. if the data entered is 200, 50, 30 then
the list look like
200 50 30
Creating a single linked list
CS 10001 : Programming and Data Stru
ctures
19
Example 1: Creating a Single Linked List
Lecture #05: © DSamanta
Linked list to store and print roll number, name and age of 3 students.
#include <stdio.h>
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
main()
{
struct stud n1, n2, n3;
struct stud *p;
scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age);
scanf (“%d %s %d”, &n2.roll,n2.name, &n2.age);
scanf (“%d %s %d”, &n3.roll,n3.name, &n3.age);
CS 10001 : Programming and Data Stru
ctures
20
Example 1: Creating a Single Linked List
Lecture #05: © DSamanta
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ;
/* Now traverse the list and print the elements */
p = &n1 ; /* point to 1st element */
while (p != NULL)
{
printf (“n %d %s %d”, p->roll, p->name, p->age);
p = p->next;
}
}
CS 10001 : Programming and Data Stru
ctures
21
Example 1: Illustration
Lecture #05: © DSamanta
The structure:
struct stud
{
int roll;
char name[30];
int age;
struct stud *next;
};
Also assume the list with three nodes n1, n2 and n3 for 3 students.
struct stud n1, n2, n3;
CS 10001 : Programming and Data Stru
ctures
22
Example 1: Illustration
Lecture #05: © DSamanta
To create the links between nodes, it is written as:
n1.next = &n2 ;
n2.next = &n3 ;
n3.next = NULL ; /* No more nodes follow */
• Now the list looks like:
roll
name
age
next
n1 n2 n3
NULL
CS 10001 : Programming and Data Stru
ctures
23
Single Linked List: Traversing
Lecture #05: © DSamanta
Once the linked list has been constructed and header points to
the first node of the list,
• Follow the pointers.
• Display the contents of the nodes as they are traversed.
• Stop when the next pointer points to NULL.
The function traverseList(struct Node *) is given in the next
slide. This function to be called from main() function as:
int main()
{
// Assume header, the pointer to the linked list is given as an input
printf("n Data in the list n");
traverseList(header);
return 0;
}
CS 10001 : Programming and Data Stru
ctures
24
Single linked list: Traversing
Lecture #05: © DSamanta
void traverseList(struct Node *header)
{
struct node *temp;
/* If the list is empty i.e. head = NULL */
if(header == NULL)
{
printf("List is empty.");
}
else
{
temp = header;
while(temp != NULL)
{
printf("Data = %dn", temp->data); //Prints the data of current node
temp = temp->next; //Advances the position of current node
}
}
}
Chandigarh Group of Colleges, Landran
TRAVERSING A LINKED LIST EXAMPLE:
CS 10001 : Programming and Data Stru
ctures
26
Single Linked List: Insertion
Lecture #05: © DSamanta
Insertion steps:
•Create a new node
•Start from the header node
•Manage links to
• Insert at front
• Insert at end
• Insert at any position
CS 10001 : Programming and Data Stru
ctures
27
Insertion at Front
Lecture #05: © DSamanta
Steps to insert node at the beginning of singly linked list
Step 1: Create a new node.
CS 10001 : Programming and Data Stru
ctures
28
Insertion at Front
Lecture #05: © DSamanta
Step 3: Make the new node as the head node, i.e. now head node will point to newNode.
Step 2: Link the newly created node with the head node, i.e. the newNode will now
point to head node.
CS 10001 : Programming and Data Stru
ctures
29
Insertion at front
Lecture #05: © DSamanta
/*Create a new node and insert at the beginning of the linked list.*/
void insertNodeAtBeginning(int data)
{
struct node *newNode;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = head; //Links the address part
head = newNode; //Makes newNode as first node
printf("DATA INSERTED SUCCESSFULLYn");
}
}
CS 10001 : Programming and Data Stru
ctures
30
Single Linked List: Insertion at End
Lecture #05: © DSamanta
Steps to insert node at the end of Singly linked list
Step 1: Create a new node and make sure that the address part of the new node points to
NULL. i.e. newNode->next=NULL
Step 2: Traverse to the last node of the linked list and connect the last node of the list with
the new node, i.e. last node will now point to new node. (lastNode->next =
newNode).
CS 10001 : Programming and Data Stru
ctures
31
Insertion at End
Lecture #05: © DSamanta
/* Create a new node and insert at the end of the linked list. */
void insertNodeAtEnd(int data)
{
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = NULL;
temp = head;
while(temp->next != NULL) //Traverse to the last node
temp = temp->next;
temp->next = newNode; //Links the address part
printf("DATA INSERTED SUCCESSFULLYn");
}
}
CS 10001 : Programming and Data Stru
ctures
32
Lecture #05: © DSamanta
Steps to insert node at any position of Singly Linked List
Step 1: Create a new node.
Single Linked List: Insertion at any Position
Step 2: Traverse to the n-1th
position of the linked list and connect the new node with the
n+1th
node. (newNode->next = temp->next) where temp is the n-1th
node.
CS 10001 : Programming and Data Stru
ctures
33
Single Linked List: Insertion at any position
Lecture #05: © DSamanta
Step 3: Now at last connect the n-1th
node with the new node i.e. the n-1th
node will now
point to new node. (temp->next = newNode) where temp is the n-1th
node.
CS 10001 : Programming and Data Stru
ctures
34
Insertion at any Position
Lecture #05: © DSamanta
/* Create a new node and insert at middle of the linked list.*/
void insertNodeAtMiddle(int data, int position)
{
int i;
struct node *newNode, *temp;
newNode = (struct node*)malloc(sizeof(struct node));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
}
else
{
newNode->data = data; //Links the data part
newNode->next = NULL;
temp = head;
CS 10001 : Programming and Data Stru
ctures
35
Insertion at any Position
Lecture #05: © DSamanta
for(i=2; i<=position-1; i++) /* Traverse to the n-1 position */
{
temp = temp->next;
if(temp == NULL)
break;
}
if(temp != NULL)
{
/* Links the address part of new node */
newNode->next = temp->next;
/* Links the address part of n-1 node */
temp->next = newNode;
printf("DATA INSERTED SUCCESSFULLYn");
}
else
{
printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn");
}
}
}
CS 10001 : Programming and Data Stru
ctures
36
Single Linked List: Deletion
Lecture #05: © DSamanta
Deletion steps
•Start from the header node
•Manage links to
• Delete at front
• Delete at end
• Delete at any position
•freeingup the node as free space.
CS 10001 : Programming and Data Stru
ctures
37
Free Memory after Deletion
Lecture #05: © DSamanta
• Do not forget to free() memory location dynamically allocated
for a node after deletion of that node.
• It is the programmer’s responsibility to free that memory
block.
• Failure to do so may create a dangling pointer – a memory,
that is not used either by the programmer or by the system.
• The content of a free memory is not erased until it is
overwritten.
CS 10001 : Programming and Data Stru
ctures
38
Lecture #05: © DSamanta
Steps to delete first node of Singly Linked List
Step 1: Copy the address of first node i.e. head node to some temp variable say toDelete.
Single Linked List: Deletion at Front
Step 2: Move the head to the second node of the linked list (head = head->next).
CS 10001 : Programming and Data Stru
ctures
39
Lecture #05: © DSamanta
Step 3: Disconnect the connection of first node to second node.
Single linked list: Deletion at front
Step 4: Free the memory occupied by the first node.
CS 10001 : Programming and Data Stru
ctures
40
Deletion at Front
Lecture #05: © DSamanta
/* Delete the first node of the linked list */
void deleteFirstNode()
{
struct node *toDelete;
if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;
head = head->next;
printf("nData deleted = %dn", toDelete->data);
/* Clears the memory occupied by first node*/
free(toDelete);
printf("SUCCESSFULLY DELETED FIRST NODE FROM LISTn");
}
}
CS 10001 : Programming and Data Stru
ctures
41
Lecture #05: © DSamanta
Steps to delete last node of a Singly Linked List
Step 1: Traverse to the last node of the linked list keeping track of the second last node in
some temp variable say secondLastNode.
Single linked list: Deletion at End
Step 2: If the last node is the head node then make the head node as NULL else disconnect
the second last node with the last node i.e. secondLastNode->next = NULL
CS 10001 : Programming and Data Stru
ctures
42
Lecture #05: © DSamanta
Step 3: Free the memory occupied by the last node.
Single linked list: Deletion at End
CS 10001 : Programming and Data Stru
ctures
43
Deletion at End
Lecture #05: © DSamanta
/* Delete the last node of the linked list */
void deleteLastNode()
{
struct node *toDelete, *secondLastNode;
toDelete = head;
secondLastNode = head;
while(toDelete->next != NULL) /* Traverse to the last node of the list*/
{
secondLastNode = toDelete;
toDelete = toDelete->next;
}
if(toDelete == head)
{
head = NULL;
}
else
{
/* Disconnects the link of second last node with last node */
secondLastNode->next = NULL;
}
/* Delete the last node */
free(toDelete);
}
CS 10001 : Programming and Data Stru
ctures
44
Lecture #05: © DSamanta
Steps to delete a node at any position of Singly Linked List
Step 1: Traverse to the nth
node of the singly linked list and also keep reference of n-1th
node
in some temp variable say prevNode.
Single Linked List: Deletion at any Position
Step 2: Reconnect n-1th
node with the n+1th
node i.e. prevNode->next = toDelete->next
(Where prevNode is n-1th
node and toDelete node is the nth
node and toDelete->next is the n+1th
node).
CS 10001 : Programming and Data Stru
ctures
45
Single Linked List: Deletion at any Position
Lecture #05: © DSamanta
Step 3: Free the memory occupied by the nth
node i.e. toDelete node.
CS 10001 : Programming and Data Stru
ctures
46
Deletion at any Position
Lecture #05: © DSamanta
/* Delete the node at any given position of the linked list */
void deleteMiddleNode(int position)
{
int i;
struct node *toDelete, *prevNode;
if(head == NULL)
{
printf("List is already empty.");
}
else
{
toDelete = head;
prevNode = head;
for(i=2; i<=position; i++)
{
prevNode = toDelete;
toDelete = toDelete->next;
if(toDelete == NULL)
break;
}
CS 10001 : Programming and Data Stru
ctures
47
Deletion at any Position
Lecture #05: © DSamanta
if(toDelete != NULL)
{
if(toDelete == head)
head = head->next;
prevNode->next = toDelete->next;
toDelete->next = NULL;
/* Deletes the n node */
free(toDelete);
printf("SUCCESSFULLY DELETED NODE FROM MIDDLE OF LISTn");
}
else
{
printf("Invalid position unable to delete.");
}
}
}

More Related Content

PPTX
Understanding Complete Linked Lists.pptx
rishjain0910
 
PPTX
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
PPTX
Deletion from single way linked list and search
Estiak Khan
 
PPT
Linked list1.ppt
KasthuriKAssistantPr
 
PPTX
Implemention of Linked list concept in Data Structures
BodapatiNagaeswari1
 
PPT
Wk11-linkedlist.ppt linked list complete iit
shalinipriya1692
 
PPT
Singly Circular Linked List – Last node points to the first node.
Bhagya775232
 
PPT
Linked List.ppt
NBACriteria2SICET
 
Understanding Complete Linked Lists.pptx
rishjain0910
 
Linked Lists, Single Linked list and its operations
BackiyalakshmiVenkat
 
Deletion from single way linked list and search
Estiak Khan
 
Linked list1.ppt
KasthuriKAssistantPr
 
Implemention of Linked list concept in Data Structures
BodapatiNagaeswari1
 
Wk11-linkedlist.ppt linked list complete iit
shalinipriya1692
 
Singly Circular Linked List – Last node points to the first node.
Bhagya775232
 
Linked List.ppt
NBACriteria2SICET
 

Similar to UNIT -4 Singly Linked List-kiruthika.pptx (20)

PPT
Wk11-linkedlist.ppt
saivasu4
 
PPT
Wk11-linkedlist.ppt
Gokiladeepa
 
PPT
Wk11-linkedlist.ppt
DevanshGupta715341
 
PPTX
Linear data structure concepts
Akila Krishnamoorthy
 
PPTX
Unit II Data Structure 2hr topic - List - Operations.pptx
Mani .S (Specialization in Semantic Web)
 
PPT
linkedlist.ppt
soniya555961
 
PPT
linkedlist (1).ppt
SwarChaudhary
 
PDF
DS Module 03.pdf
SonaPathak5
 
PDF
Lec-4_Linked-List (1).pdf
KylaMaeGarcia1
 
PPTX
linked list_MODULE 3.pptx ppt on the linked list
AnuragKumar682871
 
PPTX
Data Structure and Algorithm Lesson 2.pptx
JoannahClaireAlforqu
 
PDF
Singly Linked List
raghavbirla63
 
PPTX
link listawetewrtwertwertewrtwertwer.pptx
jokefor188
 
PPT
Wk11-linkedlist.ppt
MrsSHEEBAM
 
PPT
Wk11-linkedlist.ppt
duraimurugan alagarsamy
 
PPT
linkedlistqwerwwdderdsddsseddddddsdrr.ppt
bgmi52926
 
PPT
ANOITO2341988888888888888888888885555.ppt
robertobula2
 
PPTX
Linked list
Md. Afif Al Mamun
 
PPTX
Singly Linked List_Operations-Traversal.pptx
ssusera965f6
 
PDF
Ds lists
Dzinh Tuong
 
Wk11-linkedlist.ppt
saivasu4
 
Wk11-linkedlist.ppt
Gokiladeepa
 
Wk11-linkedlist.ppt
DevanshGupta715341
 
Linear data structure concepts
Akila Krishnamoorthy
 
Unit II Data Structure 2hr topic - List - Operations.pptx
Mani .S (Specialization in Semantic Web)
 
linkedlist.ppt
soniya555961
 
linkedlist (1).ppt
SwarChaudhary
 
DS Module 03.pdf
SonaPathak5
 
Lec-4_Linked-List (1).pdf
KylaMaeGarcia1
 
linked list_MODULE 3.pptx ppt on the linked list
AnuragKumar682871
 
Data Structure and Algorithm Lesson 2.pptx
JoannahClaireAlforqu
 
Singly Linked List
raghavbirla63
 
link listawetewrtwertwertewrtwertwer.pptx
jokefor188
 
Wk11-linkedlist.ppt
MrsSHEEBAM
 
Wk11-linkedlist.ppt
duraimurugan alagarsamy
 
linkedlistqwerwwdderdsddsseddddddsdrr.ppt
bgmi52926
 
ANOITO2341988888888888888888888885555.ppt
robertobula2
 
Linked list
Md. Afif Al Mamun
 
Singly Linked List_Operations-Traversal.pptx
ssusera965f6
 
Ds lists
Dzinh Tuong
 
Ad

Recently uploaded (20)

PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PDF
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
PDF
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
PPTX
Online Cab Booking and Management System.pptx
diptipaneri80
 
PDF
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
PPTX
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PPTX
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PDF
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
PDF
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
PPTX
Information Retrieval and Extraction - Module 7
premSankar19
 
PPTX
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
PPT
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
PPTX
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
CAD-CAM U-1 Combined Notes_57761226_2025_04_22_14_40.pdf
shailendrapratap2002
 
2010_Book_EnvironmentalBioengineering (1).pdf
EmilianoRodriguezTll
 
Online Cab Booking and Management System.pptx
diptipaneri80
 
Introduction to Ship Engine Room Systems.pdf
Mahmoud Moghtaderi
 
sunil mishra pptmmmmmmmmmmmmmmmmmmmmmmmmm
singhamit111
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
LEAP-1B presedntation xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
hatem173148
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
22PCOAM21 Session 1 Data Management.pptx
Guru Nanak Technical Institutions
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
Packaging Tips for Stainless Steel Tubes and Pipes
heavymetalsandtubes
 
The Effect of Artifact Removal from EEG Signals on the Detection of Epileptic...
Partho Prosad
 
Information Retrieval and Extraction - Module 7
premSankar19
 
MSME 4.0 Template idea hackathon pdf to understand
alaudeenaarish
 
1. SYSTEMS, ROLES, AND DEVELOPMENT METHODOLOGIES.ppt
zilow058
 
FUNDAMENTALS OF ELECTRIC VEHICLES UNIT-1
MikkiliSuresh
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
2025 Laurence Sigler - Advancing Decision Support. Content Management Ecommer...
Francisco Javier Mora Serrano
 
Ad

UNIT -4 Singly Linked List-kiruthika.pptx

  • 2. LINKED LIST Definition: • A linked list is a linear data structure where each element is a separate object. • Linked list elements are not stored at contiguous location; the elements are linked using pointers. • LINKED LIST is a collection of data elements called nodes where the linear order is given by means of pointer. • Each node of a list is made up of two items - the data and a reference to the next node. • The last node has a reference to null.
  • 4. Chandigarh Group of Colleges, Landran
  • 5. Chandigarh Group of Colleges, Landran Example of LINKED List:
  • 7. Chandigarh Group of Colleges, Landran Example of linked list :
  • 8. Chandigarh Group of Colleges, Landran Types of Linked list: • Linear or Singly linked list • Circular Linked List • Doubly Linked list
  • 9. Chandigarh Group of Colleges, Landran Singly or Linear linked list VS Circular Linked List:
  • 10. CS 10001 : Programming and Data Stru ctures 10 Lecture #05: © DSamanta Types of Lists: Circular Linked List Circular linked list • The pointer from the last element in the list points back to the first element. A B C head
  • 11. 11 Circular Linked List • A circular linked list is basically a linear linked list that may be single- or double-linked. • The only difference is that there is no any NULL value terminating the list. • In fact in the list every node points to the next node and last node points to the first node, thus forming a circle. Since it forms a circle with no end to stop it is called as circular linked list. • In circular linked list there can be no starting or ending node, whole node can be traversed from any node. • In order to traverse the circular linked list, only once we need to traverse entire list until the starting node is not traversed again. • A circular linked list can be implemented using both singly linked list and doubly linked list.
  • 12. Chandigarh Group of Colleges, Landran Single or Linear linked list VS Double Linked List:
  • 13. 13 Types of Lists: Double Linked List Double linked list • Pointers exist between adjacent nodes in both directions. • The list can be traversed either forward or backward. • Usually two pointers are maintained to keep track of the list, head and tail. A B C head tail
  • 14. Double Linked List • Doubly linked list is a collection of nodes linked together in a sequential way. • Doubly linked list is almost similar to singly linked list except it contains two address or reference fields, where one of the address field contains reference of the next node and other contains reference of the previous node. • First and last node of a linked list contains a terminator generally a NULL value, that determines the start and end of the list. • Doubly linked list is sometimes also referred as bi-directional linked list since it allows traversal of nodes in both direction. • Since doubly linked list allows the traversal of nodes in both direction, we can keep track of both first and last nodes.
  • 16. CS 10001 : Programming and Data Stru ctures 16 Operations on single linked list Lecture #05: © DSamanta • Creating a Node • Traversing a list • Printing, finding minimum, etc. • Insertion of a node into a list • At front, end and anywhere, etc. • Deletion of a node from a list • At front, end and anywhere, etc.
  • 17. CS 10001 : Programming and Data Stru ctures 17 Lecture #05: © DSamanta Defining a Node of a Linked List Each structure of the list is called a node, and consists of two fields: • Item (or) data • Address of the next item in the list (or) pointer to the next node in the list struct node { int data; /* Data */ struct node *next; /* pointer*/ } ; Data next node Note: Such structures which contain a member field pointing to the same structure type are called self-referential structures. How to define a node of a linked list?
  • 18. 18 newNode = (struct node *)malloc(sizeof(struct node)); newNode->data = data; //Links the data field of newNode with data newNode->next = NULL; //Links the address field of newNode with NULL temp->next = newNode; //Links previous node i.e. temp to the newNode temp = temp->next; head 100 NULL If we need n number of nodes in the linked list: • Allocate n newNodes, one by one. • Read in the data for the newNodes. • Modify the links of the newNodes so that the chain is formed. It creates n number of nodes . For e.g. if the data entered is 200, 50, 30 then the list look like 200 50 30 Creating a single linked list
  • 19. CS 10001 : Programming and Data Stru ctures 19 Example 1: Creating a Single Linked List Lecture #05: © DSamanta Linked list to store and print roll number, name and age of 3 students. #include <stdio.h> struct stud { int roll; char name[30]; int age; struct stud *next; }; main() { struct stud n1, n2, n3; struct stud *p; scanf (“%d %s %d”, &n1.roll, n1.name, &n1.age); scanf (“%d %s %d”, &n2.roll,n2.name, &n2.age); scanf (“%d %s %d”, &n3.roll,n3.name, &n3.age);
  • 20. CS 10001 : Programming and Data Stru ctures 20 Example 1: Creating a Single Linked List Lecture #05: © DSamanta n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* Now traverse the list and print the elements */ p = &n1 ; /* point to 1st element */ while (p != NULL) { printf (“n %d %s %d”, p->roll, p->name, p->age); p = p->next; } }
  • 21. CS 10001 : Programming and Data Stru ctures 21 Example 1: Illustration Lecture #05: © DSamanta The structure: struct stud { int roll; char name[30]; int age; struct stud *next; }; Also assume the list with three nodes n1, n2 and n3 for 3 students. struct stud n1, n2, n3;
  • 22. CS 10001 : Programming and Data Stru ctures 22 Example 1: Illustration Lecture #05: © DSamanta To create the links between nodes, it is written as: n1.next = &n2 ; n2.next = &n3 ; n3.next = NULL ; /* No more nodes follow */ • Now the list looks like: roll name age next n1 n2 n3 NULL
  • 23. CS 10001 : Programming and Data Stru ctures 23 Single Linked List: Traversing Lecture #05: © DSamanta Once the linked list has been constructed and header points to the first node of the list, • Follow the pointers. • Display the contents of the nodes as they are traversed. • Stop when the next pointer points to NULL. The function traverseList(struct Node *) is given in the next slide. This function to be called from main() function as: int main() { // Assume header, the pointer to the linked list is given as an input printf("n Data in the list n"); traverseList(header); return 0; }
  • 24. CS 10001 : Programming and Data Stru ctures 24 Single linked list: Traversing Lecture #05: © DSamanta void traverseList(struct Node *header) { struct node *temp; /* If the list is empty i.e. head = NULL */ if(header == NULL) { printf("List is empty."); } else { temp = header; while(temp != NULL) { printf("Data = %dn", temp->data); //Prints the data of current node temp = temp->next; //Advances the position of current node } } }
  • 25. Chandigarh Group of Colleges, Landran TRAVERSING A LINKED LIST EXAMPLE:
  • 26. CS 10001 : Programming and Data Stru ctures 26 Single Linked List: Insertion Lecture #05: © DSamanta Insertion steps: •Create a new node •Start from the header node •Manage links to • Insert at front • Insert at end • Insert at any position
  • 27. CS 10001 : Programming and Data Stru ctures 27 Insertion at Front Lecture #05: © DSamanta Steps to insert node at the beginning of singly linked list Step 1: Create a new node.
  • 28. CS 10001 : Programming and Data Stru ctures 28 Insertion at Front Lecture #05: © DSamanta Step 3: Make the new node as the head node, i.e. now head node will point to newNode. Step 2: Link the newly created node with the head node, i.e. the newNode will now point to head node.
  • 29. CS 10001 : Programming and Data Stru ctures 29 Insertion at front Lecture #05: © DSamanta /*Create a new node and insert at the beginning of the linked list.*/ void insertNodeAtBeginning(int data) { struct node *newNode; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; //Links the data part newNode->next = head; //Links the address part head = newNode; //Makes newNode as first node printf("DATA INSERTED SUCCESSFULLYn"); } }
  • 30. CS 10001 : Programming and Data Stru ctures 30 Single Linked List: Insertion at End Lecture #05: © DSamanta Steps to insert node at the end of Singly linked list Step 1: Create a new node and make sure that the address part of the new node points to NULL. i.e. newNode->next=NULL Step 2: Traverse to the last node of the linked list and connect the last node of the list with the new node, i.e. last node will now point to new node. (lastNode->next = newNode).
  • 31. CS 10001 : Programming and Data Stru ctures 31 Insertion at End Lecture #05: © DSamanta /* Create a new node and insert at the end of the linked list. */ void insertNodeAtEnd(int data) { struct node *newNode, *temp; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; //Links the data part newNode->next = NULL; temp = head; while(temp->next != NULL) //Traverse to the last node temp = temp->next; temp->next = newNode; //Links the address part printf("DATA INSERTED SUCCESSFULLYn"); } }
  • 32. CS 10001 : Programming and Data Stru ctures 32 Lecture #05: © DSamanta Steps to insert node at any position of Singly Linked List Step 1: Create a new node. Single Linked List: Insertion at any Position Step 2: Traverse to the n-1th position of the linked list and connect the new node with the n+1th node. (newNode->next = temp->next) where temp is the n-1th node.
  • 33. CS 10001 : Programming and Data Stru ctures 33 Single Linked List: Insertion at any position Lecture #05: © DSamanta Step 3: Now at last connect the n-1th node with the new node i.e. the n-1th node will now point to new node. (temp->next = newNode) where temp is the n-1th node.
  • 34. CS 10001 : Programming and Data Stru ctures 34 Insertion at any Position Lecture #05: © DSamanta /* Create a new node and insert at middle of the linked list.*/ void insertNodeAtMiddle(int data, int position) { int i; struct node *newNode, *temp; newNode = (struct node*)malloc(sizeof(struct node)); if(newNode == NULL) { printf("Unable to allocate memory."); } else { newNode->data = data; //Links the data part newNode->next = NULL; temp = head;
  • 35. CS 10001 : Programming and Data Stru ctures 35 Insertion at any Position Lecture #05: © DSamanta for(i=2; i<=position-1; i++) /* Traverse to the n-1 position */ { temp = temp->next; if(temp == NULL) break; } if(temp != NULL) { /* Links the address part of new node */ newNode->next = temp->next; /* Links the address part of n-1 node */ temp->next = newNode; printf("DATA INSERTED SUCCESSFULLYn"); } else { printf("UNABLE TO INSERT DATA AT THE GIVEN POSITIONn"); } } }
  • 36. CS 10001 : Programming and Data Stru ctures 36 Single Linked List: Deletion Lecture #05: © DSamanta Deletion steps •Start from the header node •Manage links to • Delete at front • Delete at end • Delete at any position •freeingup the node as free space.
  • 37. CS 10001 : Programming and Data Stru ctures 37 Free Memory after Deletion Lecture #05: © DSamanta • Do not forget to free() memory location dynamically allocated for a node after deletion of that node. • It is the programmer’s responsibility to free that memory block. • Failure to do so may create a dangling pointer – a memory, that is not used either by the programmer or by the system. • The content of a free memory is not erased until it is overwritten.
  • 38. CS 10001 : Programming and Data Stru ctures 38 Lecture #05: © DSamanta Steps to delete first node of Singly Linked List Step 1: Copy the address of first node i.e. head node to some temp variable say toDelete. Single Linked List: Deletion at Front Step 2: Move the head to the second node of the linked list (head = head->next).
  • 39. CS 10001 : Programming and Data Stru ctures 39 Lecture #05: © DSamanta Step 3: Disconnect the connection of first node to second node. Single linked list: Deletion at front Step 4: Free the memory occupied by the first node.
  • 40. CS 10001 : Programming and Data Stru ctures 40 Deletion at Front Lecture #05: © DSamanta /* Delete the first node of the linked list */ void deleteFirstNode() { struct node *toDelete; if(head == NULL) { printf("List is already empty."); } else { toDelete = head; head = head->next; printf("nData deleted = %dn", toDelete->data); /* Clears the memory occupied by first node*/ free(toDelete); printf("SUCCESSFULLY DELETED FIRST NODE FROM LISTn"); } }
  • 41. CS 10001 : Programming and Data Stru ctures 41 Lecture #05: © DSamanta Steps to delete last node of a Singly Linked List Step 1: Traverse to the last node of the linked list keeping track of the second last node in some temp variable say secondLastNode. Single linked list: Deletion at End Step 2: If the last node is the head node then make the head node as NULL else disconnect the second last node with the last node i.e. secondLastNode->next = NULL
  • 42. CS 10001 : Programming and Data Stru ctures 42 Lecture #05: © DSamanta Step 3: Free the memory occupied by the last node. Single linked list: Deletion at End
  • 43. CS 10001 : Programming and Data Stru ctures 43 Deletion at End Lecture #05: © DSamanta /* Delete the last node of the linked list */ void deleteLastNode() { struct node *toDelete, *secondLastNode; toDelete = head; secondLastNode = head; while(toDelete->next != NULL) /* Traverse to the last node of the list*/ { secondLastNode = toDelete; toDelete = toDelete->next; } if(toDelete == head) { head = NULL; } else { /* Disconnects the link of second last node with last node */ secondLastNode->next = NULL; } /* Delete the last node */ free(toDelete); }
  • 44. CS 10001 : Programming and Data Stru ctures 44 Lecture #05: © DSamanta Steps to delete a node at any position of Singly Linked List Step 1: Traverse to the nth node of the singly linked list and also keep reference of n-1th node in some temp variable say prevNode. Single Linked List: Deletion at any Position Step 2: Reconnect n-1th node with the n+1th node i.e. prevNode->next = toDelete->next (Where prevNode is n-1th node and toDelete node is the nth node and toDelete->next is the n+1th node).
  • 45. CS 10001 : Programming and Data Stru ctures 45 Single Linked List: Deletion at any Position Lecture #05: © DSamanta Step 3: Free the memory occupied by the nth node i.e. toDelete node.
  • 46. CS 10001 : Programming and Data Stru ctures 46 Deletion at any Position Lecture #05: © DSamanta /* Delete the node at any given position of the linked list */ void deleteMiddleNode(int position) { int i; struct node *toDelete, *prevNode; if(head == NULL) { printf("List is already empty."); } else { toDelete = head; prevNode = head; for(i=2; i<=position; i++) { prevNode = toDelete; toDelete = toDelete->next; if(toDelete == NULL) break; }
  • 47. CS 10001 : Programming and Data Stru ctures 47 Deletion at any Position Lecture #05: © DSamanta if(toDelete != NULL) { if(toDelete == head) head = head->next; prevNode->next = toDelete->next; toDelete->next = NULL; /* Deletes the n node */ free(toDelete); printf("SUCCESSFULLY DELETED NODE FROM MIDDLE OF LISTn"); } else { printf("Invalid position unable to delete."); } } }