题意:实现一个链表的排序,要求时间复杂度是n*lgn,空间复杂度是常数级
题意分析:该题考点——排序算法之二路归并,即先分割排序,后合并,有两种实现方式:一、递归实现;二、迭代实现。由于要求空间复杂度是常数级,所以是要求用的是迭代去实现。这里两种方式都实现一下(递归代码看起来简单易懂,迭代稍微复杂些,这里就直接粘贴复制了网友的方法)
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
//方法一:二路归并排序算法,递归实现(有一点必须明确,链表分割后,应该将每个链表当成单独的链表,所以需要确保链表的末尾指向nullptr)
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head) return nullptr;
return recursion(head);
}
ListNode* recursion(ListNode* begin);
ListNode* listMerge(ListNode* list1, ListNode* list2);
};
ListNode* Solution::recursion(ListNode* begin) {
if (begin->next == nullptr)
return begin;
ListNode* fast = begin;
ListNode* slow = begin;
ListNode* temp = slow;
while (fast != nullptr &&fast->next != nullptr)
{
fast = fast->next->next;
temp = slow;
slow = slow->next;
}
temp->next = nullptr;
return listMerge(recursion(begin), recursion(slow));
}
ListNode* Solution::listMerge(ListNode* list1,ListNode* list2) {
ListNode* list, *ptr;
if (list1->val <= list2->val)
{
list = list1;
list1 = list1->next;
}
else
{
list = list2;
list2 = list2->next;
}
ptr = list;
while (list1 && list2)
{
if (list1->val <= list2->val)
{
ptr->next = list1;
list1 = list1->next;
ptr = ptr->next;
}
else
{
ptr->next = list2;
list2 = list2->next;
ptr = ptr->next;
}
}
if (list1)
{
ptr->next = list1;
}
else
ptr->next = list2;
return list;
}
//方法二:二路归并排序算法,迭代实现(直接复制网友的答案),这也是固定的模板,参考https://blog.csdn.net/chencangui/article/details/44680113
class Solution {
public:
ListNode* sortList(ListNode* head) {
ListNode* cur = head;
int len = 0;
while (cur != NULL) {
len++;
cur = cur->next;
}
ListNode* dummy = new ListNode();
dummy->next = head;
for (int i = 1; i < len; i <<= 1) { //链表里的for循环,非常骚
cur = dummy->next;
ListNode* tail = dummy;
while (cur != NULL) {
ListNode* left = cur;
ListNode* right = split(left, i);
cur = split(right, i);
tail = merge(left, right, tail);
}
}
return dummy->next;
}
ListNode* split(ListNode* head, int size) {
for (int i = 1; head != NULL && i < size; i++) {
head = head->next;
}
if (head == NULL) return NULL;
ListNode* second = head->next;
head->next = NULL;
return second;
}
ListNode* merge(ListNode* l1, ListNode* l2, ListNode* head) {
ListNode* cur = head;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
cur->next = l1;
cur = cur->next;
l1 = l1->next;
}
else {
cur->next = l2;
cur = cur->next;
l2 = l2->next;
}
}
cur->next = (l1 == NULL) ? l2 : l1;
while (cur->next != NULL) cur = cur->next;
return cur;
}
};