-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path147.cpp
More file actions
26 lines (24 loc) · 807 Bytes
/
147.cpp
File metadata and controls
26 lines (24 loc) · 807 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
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 Problem147 {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* prev = head;
for (ListNode* temp = head->next; temp; temp = temp->next){
if (temp->val < prev->val){
prev->next = temp->next;
ListNode* pre = nullptr;
for (ListNode* iter = head; iter && iter->val < temp->val; iter = iter->next) pre = iter;
if (pre) temp->next = pre->next, pre->next = temp;
else temp->next = head, head = temp;
}
prev = temp;
}
return head;
}
};