Leetcode 147. Insertion Sort List
Given the head of a singly linked list, return the list after sorting it in ascending order using the insertion sort algorithm.
nullptr
.Here is the code implementation in C++:
/**
* 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) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head || !head->next) return head;
// Create a dummy node to serve as the new head of the sorted list.
ListNode* dummy = new ListNode(INT_MIN);
dummy->next = head;
ListNode* curr = head;
// While there are nodes left in the original list
while (curr && curr->next) {
if (curr->val <= curr->next->val) {
curr = curr->next; // Already in order; move to next element
} else {
// Extract the node to be repositioned
ListNode* toInsert = curr->next;
curr->next = curr->next->next;
// Find the position to insert the node in the sorted part of the list
ListNode* prev = dummy;
while (prev->next->val < toInsert->val) {
prev = prev->next;
}
// Insert the node into the sorted part
toInsert->next = prev->next;
prev->next = toInsert;
}
}
// Return the sorted list starting from the node next to the dummy.
return dummy->next;
}
};
Best case: O(n) - If the list is already sorted, we only traverse it once.
Average and Worst case: O(n^2) - For each node, we traverse a part of the list to find the correct insertion place.
Space Complexity: O(1) - The sorting is done in-place, so no additional memory besides a few pointers is used.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?