-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.sort-list.cpp
More file actions
101 lines (93 loc) · 1.93 KB
/
148.sort-list.cpp
File metadata and controls
101 lines (93 loc) · 1.93 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
92
93
94
95
96
97
98
99
100
101
/*
* @lc app=leetcode id=148 lang=cpp
*
* [148] Sort List
*
* https://leetcode.com/problems/sort-list/description/
*
* algorithms
* Medium (32.34%)
* Likes: 1845
* Dislikes: 95
* Total Accepted: 214.9K
* Total Submissions: 565.6K
* 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
*
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
class Solution {
public:
ListNode* merge(ListNode* first, ListNode* second) {
ListNode* return_list = nullptr;
ListNode** current = &return_list;
while (first && second) {
if (first->val <= second->val) {
*current = first;
first = first->next;
} else {
*current = second;
second = second->next;
}
current = &((*current)->next);
}
if (first) {
*current = first;
} else {
(*current) = second;
}
return return_list;
}
ListNode* divide(ListNode* head) {
if (head->next) {
ListNode* slow_ptr = head;
ListNode* fast_ptr = head;
while (fast_ptr->next && fast_ptr->next->next) {
slow_ptr = slow_ptr->next;
fast_ptr = fast_ptr->next->next;
}
ListNode* first = head;
ListNode* second = slow_ptr->next;
slow_ptr->next = nullptr;
if (fast_ptr->next) {
fast_ptr->next->next = nullptr;
}
first = divide(first);
second = divide(second);
return merge(first, second);
} else {
return head;
}
}
ListNode* sortList(ListNode* head) {
if (!head) {
return head;
}
ListNode* sorted = divide(head);
return sorted;
}
};
// @lc code=end