VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insertion-sort-for-singly-linked-list/

⇱ Insertion Sort for Singly Linked List - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insertion Sort for Singly Linked List

Last Updated : 23 Jul, 2025

Given a singly linked list, the task is to sort the list (in ascending order) using the insertion sort algorithm.

Examples:

Input: 5->4->1->3->2
Output: 1->2->3->4->5

Input: 4->3->2->1
Output: 1->2->3->4

The prerequisite is Insertion Sort on Array. The idea is to gradually build a sorted portion of the list within the same memory space as the original list.

Step-by-step approach:

  • Start with an initially empty "sorted" list, which will be built by rearranging nodes from the original list.
  • Traverse the original linked list one node at a time.
    • For each node, find its correct position within the "sorted" portion of the list.
    • If the node should be placed at the beginning (i.e., it's smaller than the first node in the sorted list), it becomes the new head of the sorted list.
    • Otherwise, traverse the sorted list to find the correct position and insert the node there.
  • Continue this process until all nodes from the original list have been repositioned in the sorted order
  • Return the head of sorted list.

Below is the implementation of the above approach


Output
 1 2 3 4 5

Time Complexity: O(n2), In the worst case, we might have to traverse all nodes of the sorted list for inserting a node.
Auxiliary Space: O(1), No extra space is required

Comment
Article Tags: