SlideShare a Scribd company logo
1 of 25
0ICPC202: Data Structures
Dr. S. Mani
Department of Computer Science and Engineering
(IoT and Cyber Security including Blockchain Technology)
ADCET, ASHTA.
Basic Linked List Operations
• Inserting an element
• Functions to Insert a new node at the beginning of the linked list
• Functions to Insert a new node after specified node
• Functions to Insert a new node at the end of the linked list
• Deleting an element
• Functions to delete a specified node from the linked list
• Displaying the contents of the linked list
• Counting the number of nodes in a linked list
• Searching in linked list
• Reversing a linked list
• Sorting the list
• Merging two linked list
Creating a Linked List
A linked list is a linear data structure that includes a series of connected nodes. Here, each
node stores the data and the address of the next node. For example,
You have to start somewhere, so we give the address of the first node a special name
called HEAD. Also, the last node in the linked list can be identified because its next portion
points to NULL.
Representation of Linked List
• Each struct node has a data item and a pointer to another struct node
struct node {
int data;
struct node *next;
};
Let us create a simple Linked List with three items to understand how this works.
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Assign data values */
one->data = 1;
two->data = 2;
three->data=3;
/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;
/* Save address of first node in head */
head = one;
malloc function can be used to allocate a block memory . It reserves a specified size of memory and returns a pointer of
type void and takes the following form int *y; // y is the integer pointer
ptr=(cast-type*) malloc (byte-size) ex. y= =(int*) malloc (100*sizeof(int)) ;
note: y is assigned with the address of the first byte of the allocated memory
After executing the code the following Linked
list is created
Things to Remember about Linked List
head points to the first node of the linked list
next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list.
In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below:
struct node {
int data;
struct node *next;
};
Over all Linked list code in C Language
// Linked list implementation in C
#include <stdio.h>
#include <stdlib.h>
// Creating a node
struct node {
int value;
struct node *next;
};
// print the linked list value
void printLinkedlist(struct node *p)
{
while (p != NULL) {
printf("%d ", p->value);
p = p->next;
}
}
int main() {
// Initialize nodes
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
// Allocate memory
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
// Assign value values
one->value = 1;
two->value = 2;
three->value = 3;
// Connect nodes
one->next = two;
two->next = three;
three->next = NULL;
// printing node-value
head = one;
printLinkedlist(head);
}
Traverse a Linked List
• Displaying the contents of a linked list is very simple. We keep moving
the temp node to the next one and display its contents.
• When temp is NULL, we know that we have reached the end of the
linked list so we get out of the while loop.
Output is
List elements are - 1 --->2 --->3 --->
struct node *temp = head;
printf("nnList elements are - n");
while(temp != NULL) {
printf("%d --->",temp->data);
temp = temp->next;
}
Inserting Element
The power of a linked list comes from the ability to break the chain and rejoin it.
• Insert a new node at the beginning of the linked list
• Insert a new node after specified node
• Insert a new node at the end of the linked list
Insert a new node at the beginning of the linked list
• Assume that already we have 3 nodes and wish to insert a new node in
the beginning of the list.
1. Insert at the beginning
• Allocate memory for new node
• Store data
• Change next of new node to point to head
• Change head to point to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = head;
head = newNode;
Insert a new node at the specified location of the linked list
3. Insert at the Middle
• Allocate memory and store data for new node
• Traverse to node just before the required position of new node
• Change next pointers to include new node in between
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
struct node *temp = head;
for(int i=2; i < position; i++) {
if(temp->next != NULL) {
temp = temp->next;
}
}
newNode->next = temp->next;
temp->next = newNode;
Insert a new node at the end of the linked list
• Assume that already we have 3 nodes and wish to insert a new node
at the end of the list.
• 2. Insert at the End
• Allocate memory for new node
• Store data
• Traverse to last node
• Change next of last node to recently created node
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = 4;
newNode->next = NULL;
struct node *temp = head;
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
Deleting an Element
You can delete either from the beginning, end or from a particular position.
1. Delete from beginning
• Point head to the second node
head = head->next;
2. Delete from end
• Traverse to second last element
• Change its next pointer to null
struct node* temp = head;
while(temp->next->next!=NULL){
temp = temp->next;
}
temp->next = NULL;
3. Delete from middle
• Traverse to element before the element to be deleted
• Change next pointers to exclude the node from the chain
for(int i=2; i< position; i++) {
if(temp->next!=NULL) {
temp = temp->next;
}
}
temp->next = temp->next->next;
Search an Element on a Linked List
You can search an element on a linked list using a loop using the following steps. i.e we are
finding item on a linked list.
• Make head as the current node.
• Run a loop until the current node is NULL because the last element points to NULL.
• In each iteration, check if the key of the node is equal to item. If it the key matches
the item, return true otherwise return false.
// Search a node
bool searchNode(struct node** head_ref, int key) {
struct node* current = *head_ref;
while (current != NULL) {
if (current->data == key)
return true;
current = current->next;
}
return false;
}
Sort Elements of a Linked List
we will use a simple sorting algorithm, Bubble Sort, to sort the elements of a linked list in ascending order
below.
1. Make the head as the current node and create another node index for later use.
2. If head is null, return.
3. Else, run a loop till the last node (i.e. NULL).
4. In each iteration, follow the following step 5-6.
5. Store the next node of current in index.
6. Check if the data of the current node is greater than the next node. If it is greater,
swap current and index.
// Sort the linked list
void sortLinkedList(struct node** head_ref)
{
struct node *current = *head_ref, *index = NULL;
int temp;
if (head_ref == NULL)
{
return;
}
else
{
while (current != NULL) {
// index points to the node next to current
index = current->next;
while (index != NULL) {
if (current->data > index->data) {
temp = current->data;
current->data = index->data;
index->data = temp;
}
index = index->next;
}
current = current->next;
}
}
}
Reversing a linked list
Sorting the list
Unit II  Data Structure 2hr topic - List - Operations.pptx

More Related Content

Similar to Unit II Data Structure 2hr topic - List - Operations.pptx

Linked list and its operations - Traversal
Linked list and its operations - TraversalLinked list and its operations - Traversal
Linked list and its operations - Traversalkasthurimukila
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTbinakasehun2026
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxMeghaKulkarni27
 
Data structure
Data structureData structure
Data structureNida Ahmed
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocationkiran Patel
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfrohit219406
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and searchEstiak Khan
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked ListThenmozhiK5
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptxjack881
 

Similar to Unit II Data Structure 2hr topic - List - Operations.pptx (20)

Linked list and its operations - Traversal
Linked list and its operations - TraversalLinked list and its operations - Traversal
Linked list and its operations - Traversal
 
DSModule2.pptx
DSModule2.pptxDSModule2.pptx
DSModule2.pptx
 
module 3-.pptx
module 3-.pptxmodule 3-.pptx
module 3-.pptx
 
Data structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LISTData structure and algorithms chapter three LINKED LIST
Data structure and algorithms chapter three LINKED LIST
 
linkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptxlinkedlist-130914084342-phpapp02.pptx
linkedlist-130914084342-phpapp02.pptx
 
Data structure
Data structureData structure
Data structure
 
Linked list using Dynamic Memory Allocation
Linked list using Dynamic Memory AllocationLinked list using Dynamic Memory Allocation
Linked list using Dynamic Memory Allocation
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Data Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdfData Structures in C++I am really new to C++, so links are really .pdf
Data Structures in C++I am really new to C++, so links are really .pdf
 
DSA(1).pptx
DSA(1).pptxDSA(1).pptx
DSA(1).pptx
 
Linked list1.ppt
Linked list1.pptLinked list1.ppt
Linked list1.ppt
 
LinkedDoublyLists.ppt
LinkedDoublyLists.pptLinkedDoublyLists.ppt
LinkedDoublyLists.ppt
 
17 linkedlist (1)
17 linkedlist (1)17 linkedlist (1)
17 linkedlist (1)
 
Linkedlist
LinkedlistLinkedlist
Linkedlist
 
Deletion from single way linked list and search
Deletion from single way linked list and searchDeletion from single way linked list and search
Deletion from single way linked list and search
 
Lec3-Linked list.pptx
Lec3-Linked list.pptxLec3-Linked list.pptx
Lec3-Linked list.pptx
 
Unit - 2.pdf
Unit - 2.pdfUnit - 2.pdf
Unit - 2.pdf
 
Data Structures_Linked List
Data Structures_Linked ListData Structures_Linked List
Data Structures_Linked List
 
UNIT 3a.pptx
UNIT 3a.pptxUNIT 3a.pptx
UNIT 3a.pptx
 
Team 10
Team 10Team 10
Team 10
 

Recently uploaded

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Unit II Data Structure 2hr topic - List - Operations.pptx

  • 1. 0ICPC202: Data Structures Dr. S. Mani Department of Computer Science and Engineering (IoT and Cyber Security including Blockchain Technology) ADCET, ASHTA.
  • 2. Basic Linked List Operations • Inserting an element • Functions to Insert a new node at the beginning of the linked list • Functions to Insert a new node after specified node • Functions to Insert a new node at the end of the linked list • Deleting an element • Functions to delete a specified node from the linked list • Displaying the contents of the linked list • Counting the number of nodes in a linked list • Searching in linked list • Reversing a linked list • Sorting the list • Merging two linked list
  • 3. Creating a Linked List A linked list is a linear data structure that includes a series of connected nodes. Here, each node stores the data and the address of the next node. For example, You have to start somewhere, so we give the address of the first node a special name called HEAD. Also, the last node in the linked list can be identified because its next portion points to NULL.
  • 4. Representation of Linked List • Each struct node has a data item and a pointer to another struct node struct node { int data; struct node *next; };
  • 5. Let us create a simple Linked List with three items to understand how this works. /* Initialize nodes */ struct node *head; struct node *one = NULL; struct node *two = NULL; struct node *three = NULL; /* Allocate memory */ one = malloc(sizeof(struct node)); two = malloc(sizeof(struct node)); three = malloc(sizeof(struct node)); /* Assign data values */ one->data = 1; two->data = 2; three->data=3; /* Connect nodes */ one->next = two; two->next = three; three->next = NULL; /* Save address of first node in head */ head = one; malloc function can be used to allocate a block memory . It reserves a specified size of memory and returns a pointer of type void and takes the following form int *y; // y is the integer pointer ptr=(cast-type*) malloc (byte-size) ex. y= =(int*) malloc (100*sizeof(int)) ; note: y is assigned with the address of the first byte of the allocated memory
  • 6. After executing the code the following Linked list is created Things to Remember about Linked List head points to the first node of the linked list next pointer of the last node is NULL, so if the next current node is NULL, we have reached the end of the linked list. In all of the examples, we will assume that the linked list has three nodes 1 --->2 --->3 with node structure as below: struct node { int data; struct node *next; };
  • 7. Over all Linked list code in C Language // Linked list implementation in C #include <stdio.h> #include <stdlib.h> // Creating a node struct node { int value; struct node *next; }; // print the linked list value void printLinkedlist(struct node *p) { while (p != NULL) { printf("%d ", p->value); p = p->next; } } int main() { // Initialize nodes struct node *head; struct node *one = NULL; struct node *two = NULL; struct node *three = NULL; // Allocate memory one = malloc(sizeof(struct node)); two = malloc(sizeof(struct node)); three = malloc(sizeof(struct node)); // Assign value values one->value = 1; two->value = 2; three->value = 3; // Connect nodes one->next = two; two->next = three; three->next = NULL; // printing node-value head = one; printLinkedlist(head); }
  • 8. Traverse a Linked List • Displaying the contents of a linked list is very simple. We keep moving the temp node to the next one and display its contents. • When temp is NULL, we know that we have reached the end of the linked list so we get out of the while loop. Output is List elements are - 1 --->2 --->3 ---> struct node *temp = head; printf("nnList elements are - n"); while(temp != NULL) { printf("%d --->",temp->data); temp = temp->next; }
  • 9. Inserting Element The power of a linked list comes from the ability to break the chain and rejoin it. • Insert a new node at the beginning of the linked list • Insert a new node after specified node • Insert a new node at the end of the linked list
  • 10. Insert a new node at the beginning of the linked list • Assume that already we have 3 nodes and wish to insert a new node in the beginning of the list. 1. Insert at the beginning • Allocate memory for new node • Store data • Change next of new node to point to head • Change head to point to recently created node struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = head; head = newNode;
  • 11. Insert a new node at the specified location of the linked list 3. Insert at the Middle • Allocate memory and store data for new node • Traverse to node just before the required position of new node • Change next pointers to include new node in between struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; struct node *temp = head; for(int i=2; i < position; i++) { if(temp->next != NULL) { temp = temp->next; } } newNode->next = temp->next; temp->next = newNode;
  • 12. Insert a new node at the end of the linked list • Assume that already we have 3 nodes and wish to insert a new node at the end of the list. • 2. Insert at the End • Allocate memory for new node • Store data • Traverse to last node • Change next of last node to recently created node struct node *newNode; newNode = malloc(sizeof(struct node)); newNode->data = 4; newNode->next = NULL; struct node *temp = head; while(temp->next != NULL){ temp = temp->next; } temp->next = newNode;
  • 13. Deleting an Element You can delete either from the beginning, end or from a particular position. 1. Delete from beginning • Point head to the second node head = head->next; 2. Delete from end • Traverse to second last element • Change its next pointer to null struct node* temp = head; while(temp->next->next!=NULL){ temp = temp->next; } temp->next = NULL;
  • 14. 3. Delete from middle • Traverse to element before the element to be deleted • Change next pointers to exclude the node from the chain for(int i=2; i< position; i++) { if(temp->next!=NULL) { temp = temp->next; } } temp->next = temp->next->next;
  • 15. Search an Element on a Linked List You can search an element on a linked list using a loop using the following steps. i.e we are finding item on a linked list. • Make head as the current node. • Run a loop until the current node is NULL because the last element points to NULL. • In each iteration, check if the key of the node is equal to item. If it the key matches the item, return true otherwise return false.
  • 16. // Search a node bool searchNode(struct node** head_ref, int key) { struct node* current = *head_ref; while (current != NULL) { if (current->data == key) return true; current = current->next; } return false; }
  • 17. Sort Elements of a Linked List we will use a simple sorting algorithm, Bubble Sort, to sort the elements of a linked list in ascending order below. 1. Make the head as the current node and create another node index for later use. 2. If head is null, return. 3. Else, run a loop till the last node (i.e. NULL). 4. In each iteration, follow the following step 5-6. 5. Store the next node of current in index. 6. Check if the data of the current node is greater than the next node. If it is greater, swap current and index.
  • 18. // Sort the linked list void sortLinkedList(struct node** head_ref) { struct node *current = *head_ref, *index = NULL; int temp; if (head_ref == NULL) { return; } else { while (current != NULL) { // index points to the node next to current index = current->next; while (index != NULL) { if (current->data > index->data) { temp = current->data; current->data = index->data; index->data = temp; } index = index->next; } current = current->next; } } }
  • 20.
  • 21.
  • 22.
  • 23.