706394. Insertion Sort for Singly Linked List

Medium

Insertion Sort for Singly Linked List

Slug: insertion-sort-for-singly-linked-list Difficulty: Medium Id: 706394 Topic Tags: Linked List, Data Structures Company Tags: Microsoft

Summary

This problem involves sorting a singly linked list using the insertion sort algorithm. The key concepts involved are linked lists and the insertion sort algorithm. The goal is to arrange the nodes of the linked list in ascending order.

Detailed Explanation

To solve this problem, we will implement the insertion sort algorithm for a singly linked list. The basic idea behind the insertion sort algorithm is to iterate through the list one node at a time, inserting each node into its proper position in a new sorted list.

Here's a step-by-step breakdown of the solution:

  1. Initialize three pointers: current, prev, and head. Set current to point to the first node in the linked list (head). Set prev to null.
  2. While current is not null:
    • Move prev to the current node.
    • If current->data is less than or equal to prev->data, break out of the loop, as we've found the correct position for the current node.
    • Move current one step forward in the list.
  3. Insert the current node into its proper position:
    • Create a new node with the same data as the current node.
    • Set the next pointer of this new node to the node that was previously at the correct position (prev->next).
    • Update prev->next to point to the new node.
  4. Repeat steps 2 and 3 until the end of the linked list is reached.

Time complexity: O(n^2), where n is the number of nodes in the linked list. Space complexity: O(1), as we're not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public class SinglyLinkedList {
    public void insertionSort(SinglyLinkedList head) {
        if (head == null || head.next == null) {
            return;
        }
        
        Node current = head;
        while (current != null) {
            Node prev = head;
            while (prev.next != current && prev.data <= current.data) {
                prev = prev.next;
            }
            
            // Insert the current node into its proper position
            Node newNode = new Node(current.data);
            newNode.next = current.next;
            current.next = newNode;
            
            current = current.next;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.