SlideShare a Scribd company logo
1 of 6
Download to read offline
How to do insertion sort on a singly linked list with no header using C?
Solution
/* C program for insertion sort on a linked list */
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
// Function to insert a given node in a sorted linked list
void sortedInsert(struct node**, struct node*);
// function to sort a singly linked list using insertion sort
void insertionSort(struct node **head_ref)
{
// Initialize sorted linked list
struct node *sorted = NULL;
// Traverse the given linked list and insert every
// node to sorted
struct node *current = *head_ref;
while (current != NULL)
{
// Store next for next iteration
struct node *next = current->next;
// insert current in sorted linked list
sortedInsert(&sorted, current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
*head_ref = sorted;
}
/* function to insert a new_node in a list. Note that this
function expects a pointer to head_ref as this can modify the
head of the input linked list (similar to push())*/
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */
/* Function to print linked list */
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* A utility function to insert a node at the beginning of linked list */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = new node;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Driver program to test above functions
int main()
{
struct node *a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
printf("Linked List before sorting  ");
printList(a);
insertionSort(&a);
printf(" Linked List after sorting  ");
printList(a);
return 0;
}
/* C program for insertion sort on a linked list */
#include
#include
/* Link list node */
struct node
{
int data;
struct node* next;
};
// Function to insert a given node in a sorted linked list
void sortedInsert(struct node**, struct node*);
// function to sort a singly linked list using insertion sort
void insertionSort(struct node **head_ref)
{
// Initialize sorted linked list
struct node *sorted = NULL;
// Traverse the given linked list and insert every
// node to sorted
struct node *current = *head_ref;
while (current != NULL)
{
// Store next for next iteration
struct node *next = current->next;
// insert current in sorted linked list
sortedInsert(&sorted, current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
*head_ref = sorted;
}
/* function to insert a new_node in a list. Note that this
function expects a pointer to head_ref as this can modify the
head of the input linked list (similar to push())*/
void sortedInsert(struct node** head_ref, struct node* new_node)
{
struct node* current;
/* Special case for the head end */
if (*head_ref == NULL || (*head_ref)->data >= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
current->next->data < new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */
/* Function to print linked list */
void printList(struct node *head)
{
struct node *temp = head;
while(temp != NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}
}
/* A utility function to insert a node at the beginning of linked list */
void push(struct node** head_ref, int new_data)
{
/* allocate node */
struct node* new_node = new node;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
// Driver program to test above functions
int main()
{
struct node *a = NULL;
push(&a, 5);
push(&a, 20);
push(&a, 4);
push(&a, 3);
push(&a, 30);
printf("Linked List before sorting  ");
printList(a);
insertionSort(&a);
printf(" Linked List after sorting  ");
printList(a);
return 0;
}

More Related Content

Similar to How to do insertion sort on a singly linked list with no header usin.pdf

I need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdfI need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdfrohit219406
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfEricvtJFraserr
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdfdeepua8
 
Use C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdfUse C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdfshalins6
 
Write java program using linked list to get integer from user and.docx
 Write java program using linked list to get integer from user and.docx Write java program using linked list to get integer from user and.docx
Write java program using linked list to get integer from user and.docxajoy21
 
Implement the following specification of UnsortedType using circular.pdf
Implement the following specification of UnsortedType using circular.pdfImplement the following specification of UnsortedType using circular.pdf
Implement the following specification of UnsortedType using circular.pdfudit652068
 
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdfin Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdfsauravmanwanicp
 
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
 
Write a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfWrite a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfkavithaarp
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdffathimahardwareelect
 
C++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docxC++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docxMatthPYNashd
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxBrianGHiNewmanv
 
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docxWrite a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docxnoreendchesterton753
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdfshanki7
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfKylaMaeGarcia1
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfJUSTSTYLISH3B2MOHALI
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxtienlivick
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfsales98
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdffortmdu
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfcallawaycorb73779
 

Similar to How to do insertion sort on a singly linked list with no header usin.pdf (20)

I need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdfI need to implment a function that can reverse a single linked list..pdf
I need to implment a function that can reverse a single linked list..pdf
 
This assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdfThis assignment and the next (#5) involve design and development of a.pdf
This assignment and the next (#5) involve design and development of a.pdf
 
C code on linked list #include stdio.h #include stdlib.h.pdf
 C code on linked list #include stdio.h #include stdlib.h.pdf C code on linked list #include stdio.h #include stdlib.h.pdf
C code on linked list #include stdio.h #include stdlib.h.pdf
 
Use C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdfUse C++ Write a function to merge two doubly linked lists. The input.pdf
Use C++ Write a function to merge two doubly linked lists. The input.pdf
 
Write java program using linked list to get integer from user and.docx
 Write java program using linked list to get integer from user and.docx Write java program using linked list to get integer from user and.docx
Write java program using linked list to get integer from user and.docx
 
Implement the following specification of UnsortedType using circular.pdf
Implement the following specification of UnsortedType using circular.pdfImplement the following specification of UnsortedType using circular.pdf
Implement the following specification of UnsortedType using circular.pdf
 
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdfin Java (ignore the last line thats hidden) Create a doubly linked l.pdf
in Java (ignore the last line thats hidden) Create a doubly linked l.pdf
 
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
 
Write a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdfWrite a program in C that does the followinga) Builds a simple li.pdf
Write a program in C that does the followinga) Builds a simple li.pdf
 
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdfTHE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
THE CODE HAS A SEGMENTATION FAULT BUT I CANNOT FIND OUT WHERE. NEED .pdf
 
C++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docxC++ please put everthing after you answer it- thanks Complete the stub.docx
C++ please put everthing after you answer it- thanks Complete the stub.docx
 
C++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docxC++ Please write the whole code that is needed for this assignment- wr.docx
C++ Please write the whole code that is needed for this assignment- wr.docx
 
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docxWrite a C++ function that delete nodes in a doubly linkedlist- It shou.docx
Write a C++ function that delete nodes in a doubly linkedlist- It shou.docx
 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdf
 
Lec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdfLec-4_Linked-List (1).pdf
Lec-4_Linked-List (1).pdf
 
Write a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdfWrite a program that accepts an arithmetic expression of unsigned in.pdf
Write a program that accepts an arithmetic expression of unsigned in.pdf
 
coding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docxcoding in C- Create a function called reverseList that takes the head.docx
coding in C- Create a function called reverseList that takes the head.docx
 
Consider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdfConsider a double-linked linked list implementation with the followin.pdf
Consider a double-linked linked list implementation with the followin.pdf
 
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdfAssignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
Assignment isPage 349-350 #4 and #5 Use the Linked List lab.pdf
 
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdfC++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
C++ problemPart 1 Recursive Print (40 pts)Please write the recu.pdf
 

More from arihantelehyb

for the normal distrbution, the proportion in the tail beyond z= 1.5.pdf
for the normal distrbution, the proportion in the tail beyond z= 1.5.pdffor the normal distrbution, the proportion in the tail beyond z= 1.5.pdf
for the normal distrbution, the proportion in the tail beyond z= 1.5.pdfarihantelehyb
 
For a square matrix A, which vectors are orthogonal to the vectors i.pdf
For a square matrix A, which vectors are orthogonal to the vectors i.pdfFor a square matrix A, which vectors are orthogonal to the vectors i.pdf
For a square matrix A, which vectors are orthogonal to the vectors i.pdfarihantelehyb
 
Five individuals, including A and B, take seats around a circular ta.pdf
Five individuals, including A and B, take seats around a circular ta.pdfFive individuals, including A and B, take seats around a circular ta.pdf
Five individuals, including A and B, take seats around a circular ta.pdfarihantelehyb
 
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdf
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdfExplain the experiments of Griffiths (1928) and Hershey Chase (1952).pdf
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdfarihantelehyb
 
Energy doing work Fuel of the cell Working part of an enzyme (2 w.pdf
Energy doing work  Fuel of the cell  Working part of an enzyme (2 w.pdfEnergy doing work  Fuel of the cell  Working part of an enzyme (2 w.pdf
Energy doing work Fuel of the cell Working part of an enzyme (2 w.pdfarihantelehyb
 
• Define transcription• Define translation• What are the 3 steps.pdf
• Define transcription• Define translation• What are the 3 steps.pdf• Define transcription• Define translation• What are the 3 steps.pdf
• Define transcription• Define translation• What are the 3 steps.pdfarihantelehyb
 
Which of the following represents the internal environment of the bod.pdf
Which of the following represents the internal environment of the bod.pdfWhich of the following represents the internal environment of the bod.pdf
Which of the following represents the internal environment of the bod.pdfarihantelehyb
 
why does venus experience so little temperature changes compared to .pdf
why does venus experience so little temperature changes compared to .pdfwhy does venus experience so little temperature changes compared to .pdf
why does venus experience so little temperature changes compared to .pdfarihantelehyb
 
Who is considered the author of The Way of Life, which is Daoisms .pdf
Who is considered the author of The Way of Life, which is Daoisms .pdfWho is considered the author of The Way of Life, which is Daoisms .pdf
Who is considered the author of The Way of Life, which is Daoisms .pdfarihantelehyb
 
Which of the following is not a function of proteinsa.         .pdf
Which of the following is not a function of proteinsa.         .pdfWhich of the following is not a function of proteinsa.         .pdf
Which of the following is not a function of proteinsa.         .pdfarihantelehyb
 
what is the marketSolutionAccording to Britannica Market, a .pdf
what is the marketSolutionAccording to Britannica Market, a .pdfwhat is the marketSolutionAccording to Britannica Market, a .pdf
what is the marketSolutionAccording to Britannica Market, a .pdfarihantelehyb
 
What happens when two shock waves collide What happens specifically.pdf
What happens when two shock waves collide What happens specifically.pdfWhat happens when two shock waves collide What happens specifically.pdf
What happens when two shock waves collide What happens specifically.pdfarihantelehyb
 
What is input A. Any data or information that is processed and pres.pdf
What is input  A. Any data or information that is processed and pres.pdfWhat is input  A. Any data or information that is processed and pres.pdf
What is input A. Any data or information that is processed and pres.pdfarihantelehyb
 
What are the main components of the chemiosmotic mechanism in mitoch.pdf
What are the main components of the chemiosmotic mechanism in mitoch.pdfWhat are the main components of the chemiosmotic mechanism in mitoch.pdf
What are the main components of the chemiosmotic mechanism in mitoch.pdfarihantelehyb
 
Description of programYou are to write a program name InfixToPost.pdf
Description of programYou are to write a program name InfixToPost.pdfDescription of programYou are to write a program name InfixToPost.pdf
Description of programYou are to write a program name InfixToPost.pdfarihantelehyb
 
Customers arrive at bakery at an average of 10 customers per hour. W.pdf
Customers arrive at bakery at an average of 10 customers per hour. W.pdfCustomers arrive at bakery at an average of 10 customers per hour. W.pdf
Customers arrive at bakery at an average of 10 customers per hour. W.pdfarihantelehyb
 
Two different strains of a mutant phage infect a single bacterium. O.pdf
Two different strains of a mutant phage infect a single bacterium. O.pdfTwo different strains of a mutant phage infect a single bacterium. O.pdf
Two different strains of a mutant phage infect a single bacterium. O.pdfarihantelehyb
 
Consider this you have two cell lines, a macrophage cell line and a.pdf
Consider this you have two cell lines, a macrophage cell line and a.pdfConsider this you have two cell lines, a macrophage cell line and a.pdf
Consider this you have two cell lines, a macrophage cell line and a.pdfarihantelehyb
 
RNA splicing activities can be regulated in cells by various activat.pdf
RNA splicing activities can be regulated in cells by various activat.pdfRNA splicing activities can be regulated in cells by various activat.pdf
RNA splicing activities can be regulated in cells by various activat.pdfarihantelehyb
 
Required Summarize why revenue is such a critical account in most c.pdf
Required Summarize why revenue is such a critical account in most c.pdfRequired Summarize why revenue is such a critical account in most c.pdf
Required Summarize why revenue is such a critical account in most c.pdfarihantelehyb
 

More from arihantelehyb (20)

for the normal distrbution, the proportion in the tail beyond z= 1.5.pdf
for the normal distrbution, the proportion in the tail beyond z= 1.5.pdffor the normal distrbution, the proportion in the tail beyond z= 1.5.pdf
for the normal distrbution, the proportion in the tail beyond z= 1.5.pdf
 
For a square matrix A, which vectors are orthogonal to the vectors i.pdf
For a square matrix A, which vectors are orthogonal to the vectors i.pdfFor a square matrix A, which vectors are orthogonal to the vectors i.pdf
For a square matrix A, which vectors are orthogonal to the vectors i.pdf
 
Five individuals, including A and B, take seats around a circular ta.pdf
Five individuals, including A and B, take seats around a circular ta.pdfFive individuals, including A and B, take seats around a circular ta.pdf
Five individuals, including A and B, take seats around a circular ta.pdf
 
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdf
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdfExplain the experiments of Griffiths (1928) and Hershey Chase (1952).pdf
Explain the experiments of Griffiths (1928) and Hershey Chase (1952).pdf
 
Energy doing work Fuel of the cell Working part of an enzyme (2 w.pdf
Energy doing work  Fuel of the cell  Working part of an enzyme (2 w.pdfEnergy doing work  Fuel of the cell  Working part of an enzyme (2 w.pdf
Energy doing work Fuel of the cell Working part of an enzyme (2 w.pdf
 
• Define transcription• Define translation• What are the 3 steps.pdf
• Define transcription• Define translation• What are the 3 steps.pdf• Define transcription• Define translation• What are the 3 steps.pdf
• Define transcription• Define translation• What are the 3 steps.pdf
 
Which of the following represents the internal environment of the bod.pdf
Which of the following represents the internal environment of the bod.pdfWhich of the following represents the internal environment of the bod.pdf
Which of the following represents the internal environment of the bod.pdf
 
why does venus experience so little temperature changes compared to .pdf
why does venus experience so little temperature changes compared to .pdfwhy does venus experience so little temperature changes compared to .pdf
why does venus experience so little temperature changes compared to .pdf
 
Who is considered the author of The Way of Life, which is Daoisms .pdf
Who is considered the author of The Way of Life, which is Daoisms .pdfWho is considered the author of The Way of Life, which is Daoisms .pdf
Who is considered the author of The Way of Life, which is Daoisms .pdf
 
Which of the following is not a function of proteinsa.         .pdf
Which of the following is not a function of proteinsa.         .pdfWhich of the following is not a function of proteinsa.         .pdf
Which of the following is not a function of proteinsa.         .pdf
 
what is the marketSolutionAccording to Britannica Market, a .pdf
what is the marketSolutionAccording to Britannica Market, a .pdfwhat is the marketSolutionAccording to Britannica Market, a .pdf
what is the marketSolutionAccording to Britannica Market, a .pdf
 
What happens when two shock waves collide What happens specifically.pdf
What happens when two shock waves collide What happens specifically.pdfWhat happens when two shock waves collide What happens specifically.pdf
What happens when two shock waves collide What happens specifically.pdf
 
What is input A. Any data or information that is processed and pres.pdf
What is input  A. Any data or information that is processed and pres.pdfWhat is input  A. Any data or information that is processed and pres.pdf
What is input A. Any data or information that is processed and pres.pdf
 
What are the main components of the chemiosmotic mechanism in mitoch.pdf
What are the main components of the chemiosmotic mechanism in mitoch.pdfWhat are the main components of the chemiosmotic mechanism in mitoch.pdf
What are the main components of the chemiosmotic mechanism in mitoch.pdf
 
Description of programYou are to write a program name InfixToPost.pdf
Description of programYou are to write a program name InfixToPost.pdfDescription of programYou are to write a program name InfixToPost.pdf
Description of programYou are to write a program name InfixToPost.pdf
 
Customers arrive at bakery at an average of 10 customers per hour. W.pdf
Customers arrive at bakery at an average of 10 customers per hour. W.pdfCustomers arrive at bakery at an average of 10 customers per hour. W.pdf
Customers arrive at bakery at an average of 10 customers per hour. W.pdf
 
Two different strains of a mutant phage infect a single bacterium. O.pdf
Two different strains of a mutant phage infect a single bacterium. O.pdfTwo different strains of a mutant phage infect a single bacterium. O.pdf
Two different strains of a mutant phage infect a single bacterium. O.pdf
 
Consider this you have two cell lines, a macrophage cell line and a.pdf
Consider this you have two cell lines, a macrophage cell line and a.pdfConsider this you have two cell lines, a macrophage cell line and a.pdf
Consider this you have two cell lines, a macrophage cell line and a.pdf
 
RNA splicing activities can be regulated in cells by various activat.pdf
RNA splicing activities can be regulated in cells by various activat.pdfRNA splicing activities can be regulated in cells by various activat.pdf
RNA splicing activities can be regulated in cells by various activat.pdf
 
Required Summarize why revenue is such a critical account in most c.pdf
Required Summarize why revenue is such a critical account in most c.pdfRequired Summarize why revenue is such a critical account in most c.pdf
Required Summarize why revenue is such a critical account in most c.pdf
 

Recently uploaded

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
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
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
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
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 

Recently uploaded (20)

MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
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
 
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🔝
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
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
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 

How to do insertion sort on a singly linked list with no header usin.pdf

  • 1. How to do insertion sort on a singly linked list with no header using C? Solution /* C program for insertion sort on a linked list */ #include #include /* Link list node */ struct node { int data; struct node* next; }; // Function to insert a given node in a sorted linked list void sortedInsert(struct node**, struct node*); // function to sort a singly linked list using insertion sort void insertionSort(struct node **head_ref) { // Initialize sorted linked list struct node *sorted = NULL; // Traverse the given linked list and insert every // node to sorted struct node *current = *head_ref; while (current != NULL) { // Store next for next iteration struct node *next = current->next; // insert current in sorted linked list sortedInsert(&sorted, current); // Update current current = next; } // Update head_ref to point to sorted linked list *head_ref = sorted; }
  • 2. /* function to insert a new_node in a list. Note that this function expects a pointer to head_ref as this can modify the head of the input linked list (similar to push())*/ void sortedInsert(struct node** head_ref, struct node* new_node) { struct node* current; /* Special case for the head end */ if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { new_node->next = *head_ref; *head_ref = new_node; } else { /* Locate the node before the point of insertion */ current = *head_ref; while (current->next!=NULL && current->next->data < new_node->data) { current = current->next; } new_node->next = current->next; current->next = new_node; } } /* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */ /* Function to print linked list */ void printList(struct node *head) { struct node *temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; } }
  • 3. /* A utility function to insert a node at the beginning of linked list */ void push(struct node** head_ref, int new_data) { /* allocate node */ struct node* new_node = new node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // Driver program to test above functions int main() { struct node *a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); printf("Linked List before sorting "); printList(a); insertionSort(&a); printf(" Linked List after sorting "); printList(a); return 0; } /* C program for insertion sort on a linked list */ #include #include /* Link list node */ struct node { int data; struct node* next;
  • 4. }; // Function to insert a given node in a sorted linked list void sortedInsert(struct node**, struct node*); // function to sort a singly linked list using insertion sort void insertionSort(struct node **head_ref) { // Initialize sorted linked list struct node *sorted = NULL; // Traverse the given linked list and insert every // node to sorted struct node *current = *head_ref; while (current != NULL) { // Store next for next iteration struct node *next = current->next; // insert current in sorted linked list sortedInsert(&sorted, current); // Update current current = next; } // Update head_ref to point to sorted linked list *head_ref = sorted; } /* function to insert a new_node in a list. Note that this function expects a pointer to head_ref as this can modify the head of the input linked list (similar to push())*/ void sortedInsert(struct node** head_ref, struct node* new_node) { struct node* current; /* Special case for the head end */ if (*head_ref == NULL || (*head_ref)->data >= new_node->data) { new_node->next = *head_ref; *head_ref = new_node; } else
  • 5. { /* Locate the node before the point of insertion */ current = *head_ref; while (current->next!=NULL && current->next->data < new_node->data) { current = current->next; } new_node->next = current->next; current->next = new_node; } } /* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */ /* Function to print linked list */ void printList(struct node *head) { struct node *temp = head; while(temp != NULL) { printf("%d ", temp->data); temp = temp->next; } } /* A utility function to insert a node at the beginning of linked list */ void push(struct node** head_ref, int new_data) { /* allocate node */ struct node* new_node = new node; /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node; } // Driver program to test above functions
  • 6. int main() { struct node *a = NULL; push(&a, 5); push(&a, 20); push(&a, 4); push(&a, 3); push(&a, 30); printf("Linked List before sorting "); printList(a); insertionSort(&a); printf(" Linked List after sorting "); printList(a); return 0; }