您的位置:首页 > 其它

sort-list——链表、快慢指针找中间、归并排序

2017-06-07 11:29 477 查看
Sort a linked list in O(n log n) time using constant space complexity.

链表,快慢指针找中点,归并排序。

注意判断条件fast->next!=NULL&&fast->next->next!=NULL,若为fast!=NULL&&fast->next!=NULL则会出现内存溢出

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==NULL || head->next==NULL)
13             return head;
14         ListNode* slow, *fast;
15         slow=head;
16         fast=head;
17         while(fast->next!=NULL&&fast->next->next!=NULL){
18             slow=slow->next;
19             fast=fast->next->next;
20         }
21         fast=slow;
22         slow=slow->next;
23         fast->next=NULL;
24         fast=sortList(head);
25         slow=sortList(slow);
26         return merge(fast,slow);
27
28     }
29     ListNode *merge(ListNode *left, ListNode *right){
30         ListNode *res,*temp;
31         if(left==NULL){
32             res=right;
33             return res;
34         }
35         if(right==NULL){
36             res=left;
37             return res;
38         }
39         if(left->val<=right->val){
40             res=left;
41             left=left->next;
42         }else{
43             res=right;
44             right=right->next;
45         }
46         temp=res;
47         while(left!=NULL&&right!=NULL){
48             if(left->val<=right->val){
49                 temp->next=left;
50                 left=left->next;
51             }else{
52                 temp->next=right;
53                 right=right->next;
54             }
55             temp=temp->next;
56
57         }
58         if(left!=NULL){
59             temp->next=left;
60         }
61         if(right!=NULL){
62             temp->next=right;
63         }
64         return res;
65     }
66 };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: