【链表】排序链表
题目:
在 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) { // 1. 递归结束条件 if (NULL == head || NULL == head->next) { return head; } // 2. 找到中间节点并断开链表&递归下探 ListNode *midnode = middleNode(head); ListNode *righthead = midnode->next; midnode->next = NULL; ListNode *left = sortList(head); ListNode *right = sortList(righthead); // 3. 当前层业务操作(合并有序链表) return mergeTwoLists(left, right); } // 找到链表的中点 ListNode *middleNode(ListNode *head) { if (NULL == head || NULL == head->next) { return head; } ListNode *slow = head; ListNode *fast = head->next; // 注意这里, 这里和单纯的寻找链表中间节点不一致 while (fast && fast->next) { slow = slow->next; fast = fast->next->next; } return slow; } // 合并两个有序链表 ListNode *mergeTwoLists(ListNode *L, ListNode *R) { if (L == NULL) { return R; } if (R == NULL) { return L; } ListNode *sentry = new ListNode(-1); ListNode *curr = sentry; while (L && R) { if (L->val < R->val) { curr->next = L; L = L->next; } else { curr->next = R; R = R->next; } curr = curr->next; } curr->next = (L != NULL ? L : R); return sentry->next; } };