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

链表排序

时间:2015-08-31 10:09:39      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:c++   代码   链表   排序   

        可以用对数组进行排序的方法对链表进行排序,但由于链表有单向访问的特点所以用归并排序比较合理。

     ListNode *Merge(ListNode *pre1, ListNode *pre2){
        ListNode *fir = pre1 -> next;
        ListNode *sec = pre2 -> next;
        ListNode *result = new ListNode(-1);
        ListNode *p = result;
        
        while(fir != nullptr && sec != nullptr){
            if(fir -> val < sec -> val){
                p -> next = fir;
                p = p -> next;
                fir = fir -> next;
            }else{
                p -> next = sec;
                p = p -> next;
                sec = sec -> next;
            }
        }
        
        if(fir == nullptr){
            while(sec != nullptr){
                p -> next = sec;
                p = p -> next;
                sec = sec -> next;
            }
            p -> next = nullptr;
        }
        if(sec == nullptr){
            while(fir != nullptr){
                p -> next = fir;
                p = p -> next;
                fir = fir -> next;
            }
            p -> next = nullptr;
        }
        return result;
    }
    
    ListNode *MergeSort(ListNode *head, ListNode *tail){
        if(head == tail){
            ListNode *result = new ListNode(-1);
            result -> next = head;
            head -> next = nullptr;
            return result;
        }
        ListNode *mid = head;
        ListNode *fast = head;
        
        while(fast != tail && fast -> next != tail){
            mid = mid -> next;
            fast = fast -> next -> next;
        }
        ListNode *tmp = mid -> next;
        ListNode *result1 = MergeSort(head, mid);
        ListNode *result2 = MergeSort(tmp, tail);
        return Merge(result1, result2);
    }
    
    ListNode *sortList(ListNode *head){
        if(head == nullptr || head -> next == nullptr)    
            return head;
            
        ListNode *tail = head;
        while(tail -> next != nullptr)
            tail = tail -> next;
            
        ListNode *result = MergeSort(head, tail);
        return result -> next;
    }

版权声明:本文为博主原创文章,未经博主允许不得转载。

链表排序

标签:c++   代码   链表   排序   

原文地址:http://blog.csdn.net/ny_mg/article/details/48129579

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