題目描述:
在 O(n log n) 時間複雜度和常數級空間複雜度下,對鏈表進行排序。
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:
輸入: -1->5->3->4->0
輸出: -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)
{
ListNode *re_head = head;
int len = 0;
while (re_head != NULL)
{
len++;
re_head = re_head->next;
}
sort(0, len - 1, head);
return head;
}
void sort(int left, int right, ListNode *head)
{
if (left < right)
{
int mid = (left + right) / 2;
sort(left, mid, head);
sort(mid + 1, right, head);
merge(left, mid, right, head);
}
}
void merge(int left, int mid, int right, ListNode *head)
{
int loc = 0;
ListNode *left_head, *right_head, *ass_head;
ListNode *re_head = head;
ListNode *temp_list = new ListNode(0);
ListNode *temp_head = temp_list;
int i = left;
int j = mid + 1;
while (1)
{
if (loc == left)
ass_head = left_head = re_head;
if (loc == mid + 1)
{
right_head = re_head;
break;
}
re_head = re_head->next;
loc++;
}
while (i <= mid && j <= right)
{
ListNode *temp_node = new ListNode(0);
if (left_head->val < right_head->val)
{
temp_head->val = left_head->val;
left_head = left_head->next;
i++;
}
else
{
temp_head->val = right_head->val;
right_head = right_head->next;
j++;
}
temp_head->next = temp_node;
temp_head = temp_head->next;
}
while (i <= mid)
{
ListNode *temp_node = new ListNode(0);
temp_head->val = left_head->val;
left_head = left_head->next;
temp_head->next = temp_node;
temp_head = temp_head->next;
i++;
}
while (j <= right)
{
ListNode *temp_node = new ListNode(0);
temp_head->val = right_head->val;
right_head = right_head->next;
temp_head->next = temp_node;
temp_head = temp_head->next;
j++;
}
temp_head = temp_list;
while (temp_head->next != NULL)
{
ass_head->val = temp_head->val;
ass_head = ass_head->next;
temp_list = temp_head->next;
delete (temp_head);
temp_head = temp_list;
}
delete temp_head;
}
};