题目: Sort List Total Accepted: 9356 Total Submissions: 47695 My Submissions Sort a linked list in O(n log n) time using constant space complexity. Have you been asked this question in an interview? class Solution { public: ListNode *sortList(ListNode *head) { if (head == NULL || head->next == NULL) return head; //第一步:从中间分开链表(使用快慢指针) ListNode * fast_p = head, *slow_p = head; while (fast_p->next != NULL && fast_p->next->next != NULL) { fast_p = fast_p->next->next; slow_p = slow_p->next; } //第二步:分别对两段链表排序(递归) ListNode * list1 = head; ListNode * list2 = slow_p->next; slow_p->next = NULL; list1 = sortList(list1); list2 = sortList(list2); //第三步:合并 return merge(list1, list2); } ListNode * merge(ListNode * list1, ListNode * list2) {//合并两个已经排序的List if (list1 == NULL) return list2; if (list2 == NULL) return list1; ListNode dummy(-1);//小技巧 ListNode * current = &dummy; while (list1 != NULL && list2 != NULL) { if (list1->val < list2->val)//每次从List1和List2中选择小的 { current->next = list1; list1 = list1->next; current = current->next; } else { current->next = list2; list2 = list2->next; current = current->next; } } if (list1 != NULL)//如果List1还有节点 current->next = list1; if (list2 != NULL) current->next = list2; return dummy.next; } };