Skip to content

Commit d94ae50

Browse files
authored
Create 0147-insertion-sort-list.cpp
1 parent 1f4cfb0 commit d94ae50

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

cpp/0147-insertion-sort-list.cpp

+69
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
Given the head of a singly linked list, sort the list using insertion sort, and return the sorted list's head.
3+
4+
The steps of the insertion sort algorithm:
5+
6+
1. Insertion sort iterates, consuming one input element each repetition and growing a sorted output list.
7+
2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list and inserts it there.
8+
3. It repeats until no input elements remain.
9+
10+
Ex. Input: head = [4,2,1,3]
11+
Output: [1,2,3,4]
12+
13+
Time : O(N^2)
14+
Space: O(1)
15+
*/
16+
17+
18+
19+
/**
20+
* Definition for singly-linked list.
21+
* struct ListNode {
22+
* int val;
23+
* ListNode *next;
24+
* ListNode() : val(0), next(nullptr) {}
25+
* ListNode(int x) : val(x), next(nullptr) {}
26+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
27+
* };
28+
*/
29+
class Solution {
30+
public:
31+
ListNode* insertionSortList(ListNode* head) {
32+
if(head == NULL || head -> next == NULL) {
33+
return head;
34+
}
35+
36+
ListNode *ptr1 = head -> next, *sortedPtr = head;
37+
while(ptr1 != NULL) {
38+
if(ptr1 -> val < sortedPtr -> val) {
39+
ListNode *ptr2 = head, *lagPtr = head;
40+
while(true) {
41+
if(ptr2 -> val > ptr1 -> val) {
42+
if(ptr2 == head) {
43+
sortedPtr -> next = ptr1 -> next;
44+
ptr1 -> next = head;
45+
head = ptr1;
46+
ptr1 = sortedPtr -> next;
47+
break;
48+
}
49+
else {
50+
sortedPtr -> next = ptr1 -> next;
51+
ptr1 -> next = ptr2;
52+
lagPtr -> next = ptr1;
53+
ptr1 = sortedPtr -> next;
54+
break;
55+
}
56+
}
57+
lagPtr = ptr2;
58+
ptr2 = ptr2 -> next;
59+
}
60+
61+
} else {
62+
sortedPtr = sortedPtr -> next;
63+
ptr1 = ptr1 -> next;
64+
}
65+
}
66+
67+
return head;
68+
}
69+
};

0 commit comments

Comments
 (0)