-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.sort-list.cpp
More file actions
91 lines (90 loc) · 1.99 KB
/
148.sort-list.cpp
File metadata and controls
91 lines (90 loc) · 1.99 KB
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
86
87
88
89
90
91
/*
* @lc app=leetcode id=148 lang=cpp
*
* [148] Sort List
*
* https://leetcode.com/problems/sort-list/description/
*
* algorithms
* Medium (36.02%)
* Total Accepted: 192.9K
* Total Submissions: 534.4K
* Testcase Example: '[4,2,1,3]'
*
* Sort a linked list in O(n log n) time using constant space complexity.
*
* Example 1:
*
*
* Input: 4->2->1->3
* Output: 1->2->3->4
*
*
* Example 2:
*
*
* Input: -1->5->3->4->0
* Output: -1->0->3->4->5
*
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head == NULL)
return NULL;
int length = 0;
auto p = head;
while (p) {
++length;
p = p->next;
}
head = sort(head, length);
return head;
}
private:
ListNode *sort(ListNode *head, int length) {
if (length == 1)
return head;
if (length == 2) {
if (head->val < head->next->val)
return head;
ListNode *tmp = head->next;
head->next = tmp->next;
tmp->next = head;
return tmp;
}
int llen = length / 2, rlen = length - llen;
ListNode *p = head;
for (int i = 0; i < llen - 1; ++i)
p = p->next;
auto right = p->next ;
p->next = NULL;
auto left = sort(head, llen);
right = sort(right, rlen);
return merge(left, right);
}
ListNode *merge(ListNode *l, ListNode *r) {
ListNode head(0), *cur = &head;
while (l && r) {
if (l->val <= r->val) {
cur->next = l;
l = l->next;
}
else {
cur->next = r;
r = r->next;
}
cur = cur->next;
}
cur->next = l ? l : r;
return head.next;
}
};