码迷,mamicode.com
首页 > 编程语言 > 详细

链表的排序----链表的归并排序

时间:2015-08-10 17:40:12      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

链表的归并排序(LinkList merge sort)

 

首先来看看如果有两条已序(sorted)的链表 ListNode *A ,  和ListNode *B, 如何合并成一条已序的链表呢?

 

 ListNode * mergeTwoLists(ListNode *l1, ListNode *l2)
    {
       ListNode *head = new ListNode(-1);
       ListNode *p = head;
       
       for(;l1&&l2; p = p->next)
       {
           if(l1->val <l2->val)
           {
               p->next = l1;
               l1 =l1->next;
           }
           else
           {
               p->next = l2;
               l2 =l2->next;
           }
           
       }
        
         p->next = l1!=nullptr?l1:l2;
         return head->next;
         
        
    }

所以一条单链表的归并排序的思路如下: 同样是分治法

1.找到一条链表的中点节点,从中点节点断开成两条链表。

2.分别对前半部分链表和后半部分链表进行 链表的归并排序。

3.得到两部分已经排序的链表,最后进行归并链表

 

程序如下: leetcode  accepted

/**
 * 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) {
    if(head==nullptr|| head->next ==nullptr) return head;
        // get the len of the list
        ListNode * fast = head;
        ListNode * slow = head;
    
        while(fast->next!=nullptr&&fast->next->next!=nullptr)
        {
            fast = fast->next->next;
            slow = slow->next;
            
        }
        
        fast = slow;       // find the mid of the linklist
        slow = slow->next;  
        fast->next = nullptr; // cut the list to two parts;
        
        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(slow);
        
        return mergeTwoLists(l1,l2);
    }
    
    ListNode * mergeTwoLists(ListNode *l1, ListNode *l2)
    {
       ListNode *head = new ListNode(-1);
       ListNode *p = head;
       
       for(;l1&&l2; p = p->next)
       {
           if(l1->val <l2->val)
           {
               p->next = l1;
               l1 =l1->next;
           }
           else
           {
               p->next = l2;
               l2 =l2->next;
           }
           
       }
        
         p->next = l1!=nullptr?l1:l2;
         return head->next;
         
        
    }
    
};

 

链表的排序----链表的归并排序

标签:

原文地址:http://www.cnblogs.com/deanlan/p/4718519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!