C++ Program For Insertion Sort In A Singly Linked List
Last Updated :
28 Apr, 2023
We have discussed Insertion Sort for arrays. In this article we are going to discuss Insertion Sort for linked list.
Below is a simple insertion sort algorithm for a linked list.
1) Create an empty sorted (or result) list.
2) Traverse the given list, do following for every node.
......a) Insert current node in sorted way in sorted or result list.
3) Change head of given linked list to head of sorted (or result) list.
The main step is (2.a) which has been covered in the post Sorted Insert for Singly Linked List
Below is the implementation of the above algorithm:
C++
// C++ program to sort link list
// using insertion sort
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int val;
struct Node* next;
Node(int x)
{
val = x;
next = NULL;
}
};
class LinkedlistIS
{
public:
Node* head;
Node* sorted;
void push(int val)
{
// Allocate node
Node* newnode = new Node(val);
// Link the old list of the
// new node
newnode->next = head;
// Move the head to point to the
// new node
head = newnode;
}
// Function to sort a singly linked list
// using insertion sort
void insertionSort(Node* headref)
{
// Initialize sorted linked list
sorted = NULL;
Node* current = headref;
// Traverse the given linked list
// and insert every node to sorted
while (current != NULL)
{
// Store next for next iteration
Node* next = current->next;
// Insert current in sorted
// linked list
sortedInsert(current);
// Update current
current = next;
}
// Update head_ref to point to
// sorted linked list
head = 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(Node* newnode)
{
// Special case for the head end
if (sorted == NULL ||
sorted->val >= newnode->val)
{
newnode->next = sorted;
sorted = newnode;
}
else
{
Node* current = sorted;
/* Locate the node before the
point of insertion */
while (current->next != NULL &&
current->next->val < newnode->val)
{
current = current->next;
}
newnode->next = current->next;
current->next = newnode;
}
}
// Function to print linked list
void printlist(Node* head)
{
while (head != NULL)
{
cout << head->val << " ";
head = head->next;
}
}
};
// Driver code
int main()
{
LinkedlistIS list;
list.head = NULL;
list.push(5);
list.push(20);
list.push(4);
list.push(3);
list.push(30);
cout << "Linked List before sorting" <<
endl;
list.printlist(list.head);
cout << endl;
list.insertionSort(list.head);
cout << "Linked List After sorting" <<
endl;
list.printlist(list.head);
}
// This code is contributed by nirajgusain5
OutputLinked List before sorting
30 3 4 20 5
Linked List After sorting
3 4 5 20 30
Time Complexity: O(n2), in the worst case, we might have to traverse all nodes of the sorted list for inserting a node, and there are “n” such nodes.
Auxiliary Space: O(1), no extra space is required depending on the size of the input, thus it is constant.
Please refer complete article on Insertion Sort for Singly Linked List for more details!
Another Approach:
The idea behind this approach is to make use of dummy pointer variable that will store the elements of singly linked list in sorted order. Below is the insertion sort algorithm for singly linked list.
1) Create a new dummy node with a value equals to INT_MIN.
2) Traverse the given list, do following for every node:
a) Create two node pointers curr and prev, curr pointer pointing to dummy node variable and prev to nullptr.
b) Traverse the dummy node list and move pointer curr to its next node and prev to curr uptil the value of
node to which curr pointer is pointing is less than that of the head node value.
c) Create a next pointer which will point to the next of head element.
d) Make prev pointer's next pointing to head node and head node next pointing to curr pointer.
e) Now move head node pointer to its next node.
C++
#include<bits/stdc++.h>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
//inserton sort for singly linked list
ListNode* insertionSortList(ListNode* head) {
if(!head||!head->next)return head;
ListNode* dummy=new ListNode(INT_MIN);
while(head)
{
ListNode* curr=dummy,*prev=nullptr;
while(curr&&curr->val<=head->val)
{
prev=curr;
curr=curr->next;
}
ListNode* next=head->next;
prev->next=head;
head->next=curr;
head=next;
}
return dummy->next;
}
//Print function
void printlist(ListNode* head){
while (head != NULL)
{
cout << head->val << " ";
head = head->next;
}
cout<<endl;
}
// Driver code
int main()
{
ListNode *first=new ListNode(30);
ListNode *second=new ListNode(3);
ListNode *third=new ListNode(4);
ListNode *fourth=new ListNode(20);
ListNode *fifth=new ListNode(5);
first->next=second;
second->next=third;
third->next=fourth;
fourth->next=fifth;
//Linked list look like this: 30->3->4->20->5
cout << "Linked List before sorting" <<
endl;
printlist(first);
cout << endl;
ListNode* sorted=insertionSortList(first);
cout << "Linked List After sorting" <<
endl;
printlist(sorted);
}
OutputLinked List before sorting
30 3 4 20 5
Linked List After sorting
3 4 5 20 30
Time Complexity: O(n2), in the worst case, we might have to traverse all nodes of the sorted list to insert a node, and there are “n” such nodes.
Auxiliary Space: O(1), as the dummy node that we have created takes constant space.
Similar Reads
C++ Program For Inserting A Node In A Linked List Inserting a node into a linked list can be done in several ways, depending on where we want to insert the new node. Here, we'll cover four common scenarios: inserting at the front of the list, after a given node, at a specific position, and at the end of the listTable of ContentInsert a Node at the
9 min read
C++ Program For Inserting Node In The Middle Of The Linked List Given a linked list containing n nodes. The problem is to insert a new node with data x at the middle of the list. If n is even, then insert the new node after the (n/2)th node, else insert the new node after the (n+1)/2th node. Examples: Input : list: 1->2->4->5 x = 3 Output : 1->2->
5 min read
C++ Program For Rearranging A Given Linked List In-Place Given a singly linked list L0 -> L1 -> ⦠-> Ln-1 -> Ln. Rearrange the nodes in the list so that the new formed list is : L0 -> Ln -> L1 -> Ln-1 -> L2 -> Ln-2 ...You are required to do this in place without altering the nodes' values. Examples: Input: 1 -> 2 -> 3 -
7 min read
C++ Program For Insertion Sort Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array. In this article, we will learn to write a C++
3 min read
C++ Program For Removing Duplicates From A Sorted Linked List Write a function that takes a list sorted in non-decreasing order and deletes any duplicate nodes from the list. The list should only be traversed once. For example if the linked list is 11->11->11->21->43->43->60 then removeDuplicates() should convert the list to 11->21->43-
9 min read