-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path148.sort-list.cpp
More file actions
74 lines (74 loc) · 1.57 KB
/
Copy path148.sort-list.cpp
File metadata and controls
74 lines (74 loc) · 1.57 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
class Solution
{ // brute solution
public:
ListNode *sortList(ListNode *head)
{
vector<int> arr;
ListNode *temp = head;
while (temp)
{
arr.push_back(temp->val);
temp = temp->next;
}
sort(arr.begin(), arr.end());
temp = head;
for (auto it : arr)
{
temp->val = it;
temp = temp->next;
}
return head;
}
};
class Solution
{ // optimal solution using merge sort
public:
ListNode *findmid(ListNode *head)
{
ListNode *slow = head;
ListNode *fast = head->next;
while (fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode *merge(ListNode *lefthead, ListNode *righthead)
{
ListNode *dummynode = new ListNode(-1);
ListNode *temp = dummynode;
while (lefthead != NULL && righthead != NULL)
{
if (lefthead->val < righthead->val)
{
temp->next = lefthead;
temp = lefthead;
lefthead = lefthead->next;
}
else
{
temp->next = righthead;
temp = righthead;
righthead = righthead->next;
}
}
if (lefthead)
temp->next = lefthead;
else
temp->next = righthead;
return dummynode->next;
}
ListNode *sortList(ListNode *head)
{
if (head == NULL || head->next == NULL)
return head;
ListNode *middle = findmid(head);
ListNode *lefthead = head;
ListNode *righthead = middle->next;
middle->next = NULL;
lefthead = sortList(lefthead);
righthead = sortList(righthead);
return merge(lefthead, righthead);
}
};