148. 排序链表

 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  
10 // 1、使用快慢指针确定中点的位置。
11 // 2、分别对左部分和右部分递归。
12 // 3、merge 两部分链表。
13 class Solution 
14 {
15 public:
16     ListNode* sortList(ListNode* head) 
17     {
18         if(head == NULL || head->next == NULL) return head;
19         ListNode* dummy = new ListNode(-1);
20         dummy->next = head;
21         ListNode* fast = dummy;
22         ListNode* slow = dummy;
23         while(fast && fast->next && slow)
24         {
25             fast = fast->next->next;
26             slow = slow->next;
27         }
28         ListNode* right = sortList(slow->next);
29         slow->next = NULL;
30         ListNode* left = sortList(head);
31         return merge(left,right);
32     }
33 
34     //两个链表进行排序
35     ListNode* merge(ListNode* l1,ListNode* l2)
36     {
37         if(l1 == NULL) return l2;
38         if(l2 == NULL) return l1;
39         if(l1->val < l2->val)
40         {
41             l1->next = merge(l1->next,l2);
42             return l1;
43         }
44         else
45         {
46             l2->next = merge(l1,l2->next);
47             return l2;
48         }
49     }
50 };

 

posted @ 2020-03-23 15:09  Jinxiaobo0509  阅读(138)  评论(0)    收藏  举报