[InterviewBit] Insertion Sort List

Insertion Sort List

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

ListNode* reverse(ListNode* A) {
ListNode* dummy = new ListNode(-1);
while(A) {
ListNode* nxt = A->next;
A->next = dummy->next;
dummy->next = A;
A = nxt;
}
return dummy->next;
}
ListNode* Solution::insertionSortList(ListNode* A) {
ListNode* dummy = new ListNode(INT_MAX);

while(A) {
ListNode* runner = dummy;
ListNode* now = A;
A = A->next;
now->next = NULL;
while(runner->next and runner->next->val > now->val) {
runner = runner->next;
}
now->next = runner->next;
runner->next = now;
}

return reverse(dummy->next);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/15/PS/interviewbit/insertion-sort-list/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.