-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path148Sorted_list.cpp
81 lines (77 loc) · 2.47 KB
/
148Sorted_list.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head == NULL) return head;
ListNode* cur = head;
int count = 0;
while(cur->next != NULL){
if(cur->next->val < cur->val){
ListNode* temp = cur->next;
ListNode* check = head;
cur->next = cur->next->next;
while(check != NULL){
if(check == head && check->val>temp->val){
temp->next = check;
head = temp;
break;
}
else if(check->val <= temp->val && check->next->val >= temp->val){
temp->next = check->next;
check->next = temp;
break;
}
check = check->next;
}
continue;
}
cur = cur->next;
}
return head;
// ListNode* cur = head; //跑太慢
// int total = 0;
// while(cur != NULL){
// total++;
// cur = cur->next;
// }
// ListNode* temp;
// cur = head->next;
// int count = 0;
// int record = 0;
// head->next = NULL;
// while(count != total-1){
// count++;
// temp = cur;
// cur = cur->next;
// temp->next = NULL;
// ListNode* check = head;
// while(check != NULL){
// if(check == head && check->val>temp->val){
// temp->next = check;
// head = temp;
// break;
// }
// else if(check->next == NULL && check->val<temp->val){
// check->next = temp;
// temp->next = NULL;
// break;
// }
// else if(check->val <= temp->val && check->next->val >= temp->val){
// temp->next = check->next;
// check->next = temp;
// break;
// }
// check = check->next;
// }
// }
// return head;
}
};