Given the head of a singly linked list, sort the linked list in non-decreasing order using the Insertion Sort algorithm and return the head of the sorted list.
Examples:
Input:
Output: 2 -> 5 -> 8 -> 9 Explanation: After sorting the given linked list, the resultant list will be:
Input:
Output: 10 -> 20 -> 30 -> 40 -> 50 -> 60 Explanation: After sorting the given linked list, the resultant list will be:
The idea is to maintain a sorted portion of the linked list and process nodes one by one. If the current node is already in the correct position, extend the sorted portion. Otherwise, find its correct position in the sorted part and insert it there using a dummy node to simplify insertions.
Let us understand with example: Input: 40 -> 20 -> 60 -> 10 -> 50 -> 30
Initially, the sorted part contains only 40, and the remaining list is 20 -> 60 -> 10 -> 50 -> 30.
Take node 20. Since it is smaller than 40, insert it before 40. The list becomes 20 -> 40 -> 60 -> 10 -> 50 -> 30.
Take node 60. Since it is greater than the last node in the sorted part (40), it is already in the correct position. The list remains 20 -> 40 -> 60 -> 10 -> 50 -> 30.
Take node 10. Find its correct position in the sorted part and insert it before 20. The list becomes 10 -> 20 -> 40 -> 60 -> 50 -> 30.
Take node 50. Find its correct position in the sorted part and insert it between 40 and 60. The list becomes 10 -> 20 -> 40 -> 50 -> 60 -> 30.
Take node 30. Find its correct position in the sorted part and insert it between 20 and 40. The list becomes 10 -> 20 -> 30 -> 40 -> 50 -> 60.
All nodes have now been processed, so the final sorted linked list is 10 -> 20 -> 30 -> 40 -> 50 -> 60.
C++
#include<climits>#include<iostream>usingnamespacestd;classNode{public:intval;Node*next;Node(intx){val=x;next=nullptr;}};// function for insertion sort on linked listNode*insertionSort(Node*head){// Dummy node simplifies insertion at the beginning.Node*dummy=newNode(INT_MIN);dummy->next=head;// lastSorted stores the value of the last node// in the currently sorted portion.intlastSorted=INT_MIN;Node*prev=dummy;Node*curr=head;while(curr!=nullptr){// If current node is already in correct position,// extend the sorted portion.if(curr->val>=lastSorted){lastSorted=curr->val;prev=curr;curr=curr->next;continue;}// Find insertion position in sorted part.Node*pos=dummy;while(curr->val>=pos->next->val){pos=pos->next;}// Remove curr from current position.prev->next=curr->next;// Insert curr at correct position.curr->next=pos->next;pos->next=curr;curr=prev->next;}returndummy->next;}// Driver Codeintmain(){// Create linked list: 40 -> 20 -> 60 -> 10 -> 50 -> 30Node*head=newNode(40);head->next=newNode(20);head->next->next=newNode(60);head->next->next->next=newNode(10);head->next->next->next->next=newNode(50);head->next->next->next->next->next=newNode(30);head=insertionSort(head);// Print sorted linked listNode*temp=head;while(temp!=nullptr){cout<<temp->val;if(temp->next!=nullptr)cout<<" -> ";temp=temp->next;}cout<<endl;return0;}
Java
importjava.util.*;classNode{intval;Nodenext;Node(intx){val=x;next=null;}}publicclassGFG{// function for insertion sort on linked liststaticNodeinsertionSort(Nodehead){// Dummy node simplifies insertion at the beginning.Nodedummy=newNode(Integer.MIN_VALUE);dummy.next=head;// lastSorted stores the value of the last node// in the currently sorted portion.intlastSorted=Integer.MIN_VALUE;Nodeprev=dummy;Nodecurr=head;while(curr!=null){// If current node is already in correct// position, extend the sorted portion.if(curr.val>=lastSorted){lastSorted=curr.val;prev=curr;curr=curr.next;continue;}// Find insertion position in sorted part.Nodepos=dummy;while(curr.val>=pos.next.val){pos=pos.next;}// Remove curr from current position.prev.next=curr.next;// Insert curr at correct position.curr.next=pos.next;pos.next=curr;curr=prev.next;}returndummy.next;}publicstaticvoidmain(String[]args){// Create linked list: 40 -> 20 -> 60 -> 10 -> 50 ->// 30Nodehead=newNode(40);head.next=newNode(20);head.next.next=newNode(60);head.next.next.next=newNode(10);head.next.next.next.next=newNode(50);head.next.next.next.next.next=newNode(30);head=insertionSort(head);// Print sorted linked listNodetemp=head;while(temp!=null){System.out.print(temp.val);if(temp.next!=null)System.out.print(" -> ");temp=temp.next;}System.out.println();}}
Python
classNode:def__init__(self,x):self.val=xself.next=None# function for insertion sort on linked listdefinsertionSort(head):# Dummy node simplifies insertion at the beginning.dummy=Node(float('-inf'))dummy.next=head# lastSorted stores the value of the last node# in the currently sorted portion.lastSorted=float('-inf')prev=dummycurr=headwhilecurrisnotNone:# If current node is already in correct position,# extend the sorted portion.ifcurr.val>=lastSorted:lastSorted=curr.valprev=currcurr=curr.nextcontinue# Find insertion position in sorted part.pos=dummywhilecurr.val>=pos.next.val:pos=pos.next# Remove curr from current position.prev.next=curr.next# Insert curr at correct position.curr.next=pos.nextpos.next=currcurr=prev.nextreturndummy.next# Driver Codeif__name__=='__main__':# Create linked list: 40 -> 20 -> 60 -> 10 -> 50 -> 30head=Node(40)head.next=Node(20)head.next.next=Node(60)head.next.next.next=Node(10)head.next.next.next.next=Node(50)head.next.next.next.next.next=Node(30)head=insertionSort(head)# Print sorted linked listtemp=headwhiletempisnotNone:print(temp.val,end='')iftemp.nextisnotNone:print(' -> ',end='')temp=temp.nextprint()
C#
usingSystem;publicclassNode{publicintval;publicNodenext;publicNode(intx){val=x;next=null;}}publicclassGFG{// function for insertion sort on linked listpublicstaticNodeinsertionSort(Nodehead){// Dummy node simplifies insertion at the beginning.Nodedummy=newNode(int.MinValue);dummy.next=head;// lastSorted stores the value of the last node// in the currently sorted portion.intlastSorted=int.MinValue;Nodeprev=dummy;Nodecurr=head;while(curr!=null){// If current node is already in correct// position, extend the sorted portion.if(curr.val>=lastSorted){lastSorted=curr.val;prev=curr;curr=curr.next;continue;}// Find insertion position in sorted part.Nodepos=dummy;while(curr.val>=pos.next.val){pos=pos.next;}// Remove curr from current position.prev.next=curr.next;// Insert curr at correct position.curr.next=pos.next;pos.next=curr;curr=prev.next;}returndummy.next;}publicstaticvoidMain(string[]args){// Create linked list: 40 -> 20 -> 60 -> 10 -> 50 ->// 30Nodehead=newNode(40);head.next=newNode(20);head.next.next=newNode(60);head.next.next.next=newNode(10);head.next.next.next.next=newNode(50);head.next.next.next.next.next=newNode(30);head=insertionSort(head);// Print sorted linked listNodetemp=head;while(temp!=null){Console.Write(temp.val);if(temp.next!=null)Console.Write(" -> ");temp=temp.next;}Console.WriteLine();}}
JavaScript
classNode{constructor(val){this.val=val;this.next=null;}}// function for insertion sort on linked listfunctioninsertionSort(head){// Dummy node simplifies insertion at the beginning.constdummy=newNode(Number.MIN_SAFE_INTEGER);dummy.next=head;// lastSorted stores the value of the last node// in the currently sorted portion.letlastSorted=Number.MIN_SAFE_INTEGER;letprev=dummy;letcurr=head;while(curr!=null){// If current node is already in correct position,// extend the sorted portion.if(curr.val>=lastSorted){lastSorted=curr.val;prev=curr;curr=curr.next;continue;}// Find insertion position in sorted part.letpos=dummy;while(curr.val>=pos.next.val){pos=pos.next;}// Remove curr from current position.prev.next=curr.next;// Insert curr at correct position.curr.next=pos.next;pos.next=curr;curr=prev.next;}returndummy.next;}// Driver Codelethead=newNode(40);head.next=newNode(20);head.next.next=newNode(60);head.next.next.next=newNode(10);head.next.next.next.next=newNode(50);head.next.next.next.next.next=newNode(30);head=insertionSort(head);// Print sorted linked listlettemp=head;while(temp!=null){process.stdout.write(temp.val.toString());if(temp.next!=null)process.stdout.write(" -> ");temp=temp.next;}console.log();