forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertSort_List.cpp
More file actions
49 lines (43 loc) · 977 Bytes
/
InsertSort_List.cpp
File metadata and controls
49 lines (43 loc) · 977 Bytes
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
#include <iostream>
using namespace std;
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* p = new ListNode(1);
ListNode* pl=head;
p->next=NULL;
while (pl!=NULL) {
ListNode* pm=p;
while(pm->next!=NULL && pm->next->val<pl->val) pm=pm->next;
ListNode* tmp = pm->next;
pm->next=pl;
pl=pl->next;
pm->next->next=tmp;
}
pl = p->next;
delete p;
return pl;
}
};
int main() {
ListNode *p = new ListNode(1);
p->next = new ListNode(1);
ListNode *tmp = p;
while(tmp!=NULL) {
cout<<tmp->val<<endl;
tmp=tmp->next;
}
p = (new Solution())->insertionSortList(p);
cout<<"=================="<<endl;
tmp = p;
while(tmp!=NULL) {
cout<<tmp->val<<endl;
tmp=tmp->next;
}
}