706394. Insertion Sort for Singly Linked List
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:
- Initialize three pointers:
current,prev, andhead. Setcurrentto point to the first node in the linked list (head). Setprevto null. - While
currentis not null:- Move
prevto the current node. - If
current->datais less than or equal toprev->data, break out of the loop, as we've found the correct position for the current node. - Move
currentone step forward in the list.
- Move
- 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->nextto point to the new node.
- 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
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;
}
}
}