LeetCode: Sort List
Sort a linked list in O(n log n) time using constant space complexity.
地址:https://oj.leetcode.com/problems/sort-list/
算法:采用分治的思想,首先利用O(n)的时间找出链表的中间节点,然后将链表分成两个子链表,递归调用排序算法完成两个子链表的排序,最后在利用O(n)时间完成两个已排序链表的合并。代码:
1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 ListNode *sortList(ListNode *head) {
12 if (!head || !head->next) return head;
13 ListNode *head1, *head2;
14 ListNode *p, *q;
15 head1 = p = head;
16 head2 = q = head->next;
17 while(q->next){
18 p->next = q->next;
19 p = q->next;
20 if(p->next){
21 q->next = p->next;
22 q = p->next;
23 }else{
24 q->next = NULL;
25 q = p;
26 }
27 }
28 p->next = NULL;
29 q->next = NULL;
30 head1 = sortList(head1);
31 head2 = sortList(head2);
32 return merge(head1,head2);
33 }
34 ListNode *merge(ListNode *head1, ListNode *head2){
35 ListNode *head = NULL, *p = NULL;
36 while(head1 && head2){
37 if(head1->val > head2->val){
38 if(p){
39 p->next = head2;
40 } else{
41 head = head2;
42 }
43 p = head2;
44 head2 = head2->next;
45 } else{
46 if(p){
47 p->next = head1;
48 } else{
49 head = head1;
50 }
51 p = head1;
52 head1 = head1->next;
53 }
54 }
55 head1 = head1? head1 : head2;
56 if(p) p->next = head1;
57 else head = head1;
58 return head;
59 }
60
61 };