-
Notifications
You must be signed in to change notification settings - Fork 0
/
list_LC147.cpp
85 lines (83 loc) · 1.67 KB
/
list_LC147.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
82
83
84
85
/*
Insertion Sort List
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
using namespace std;
#include<list>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) :val(x), next(NULL) {}
};
/*
What's the problem?
*/
class Solution {
public:
ListNode * insertionSortList(ListNode* head) {
ListNode* dummy = new ListNode(-1);
//only one node
if (head->next == NULL)return head;
//else
dummy->next = head;
int lastMax = head->val;
ListNode* cur = head->next;//from the second node
ListNode* endPre = head;
ListNode*pre;
ListNode* temp;
while (cur != NULL) {
if (cur->val >= lastMax) {
lastMax = cur->val;
endPre = cur;
cur = cur->next;
continue;
}
pre = dummy;
while (pre->next!=NULL&&pre->next->val < cur->val) {
pre = pre->next;
}
temp = cur;
endPre->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = temp->next;
}
return dummy->next;
}
};
/*
Net solution
*/
class Solution {
public:
ListNode * insertionSortList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
//create a new list
ListNode* pre = new ListNode(-1);
//save the head node
ListNode*ans = pre;
//cur is the node in the old list
ListNode* cur = head;
while (cur != NULL) {
pre = ans;
while (pre->next != NULL && pre->next->val < cur->val) {
pre = pre->next;
}
ListNode* temp = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = temp;
}
return ans->next;
}
};