-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSortList.cpp
More file actions
43 lines (43 loc) · 1.18 KB
/
InsertionSortList.cpp
File metadata and controls
43 lines (43 loc) · 1.18 KB
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
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
if(head == NULL || head->next == NULL)
return head;
ListNode* current = head->next;
ListNode* last = head;
while(current != NULL){
ListNode* node = head;
ListNode* node_last = NULL;
while(node != current){
if(node->val > current->val){
break;
} else {
node_last = node;
node = node->next;
}
}
if(node != current){
last->next = current->next;
if(node_last != NULL){
node_last->next = current;
current->next = node;
} else {
current->next = node;
head = current;
}
current = last;
}
last = current;
current = current->next;
}
return head;
}
};