forked from moranzcw/LeetCode-NOTES
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
54 lines (51 loc) · 1.24 KB
/
solution.cpp
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
44
45
46
47
48
49
50
51
52
53
54
/**
* 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)
return head;
ListNode* curr = head -> next;
head -> next = NULL;
while(curr != NULL)
{
ListNode* tmpHead = head;
ListNode* prev = NULL;
ListNode* next = curr -> next;
while(tmpHead != NULL && tmpHead -> val <= curr -> val)
{
prev = tmpHead;
tmpHead = tmpHead -> next;
}
if(prev != NULL)
{
//insert
if(prev -> next)
{
curr -> next = prev -> next;
prev -> next = curr;
}
else
{
prev -> next = curr;
curr -> next = NULL;
}
}
else
{
curr -> next = head;
head = curr;
}
curr = next;
}
return head;
}
};