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

单链表排序(插入与归并)

时间:2015-08-02 21:38:44      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:单链表   插入排序   归并排序   

 struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

/*
 * 单链表的插入排序, 插入排序是一种稳定排序
 */
class Solution7 {
public:
    ListNode* insertionSortList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;


        ListNode *prev = head, *next = head->next;
        ListNode *tmp;


        while(next != NULL){
            if(prev->val <= next->val){//注意保持稳定性
                prev = next;
                next = next->next;
            }else{
                prev->next = next->next;


                if(head->val > next->val){//保持稳定性
                    next->next = head;
                    head = next;
                }else{
                    tmp = head;


                    while(tmp->next->val <= next->val){//保持稳定性
                        tmp = tmp->next;
                    }


                    next->next = tmp->next;
                    tmp->next = next;
                }


                next = prev->next;
            }
        }


        return head;
    }
};


/*
 * 单链表的归并排序, O(nlgn)
 */
class Solution8 {
public:
    ListNode* sortList(ListNode* head) {
        if(head == NULL || head->next == NULL)  return head;
        //1 快慢指针进行链表分割
        ListNode *fast=head, *slow = head, *prev=NULL;


        while(fast && fast->next){
            prev = slow;
            slow = slow->next;
            fast = fast->next->next;
        }


        prev->next = NULL;


        //2 二分
        ListNode *left_head = sortList(head);
        ListNode *right_head = sortList(slow);


        //3 合并
        ListNode dummy(-1);
        prev = &dummy;


        while(left_head && right_head){
            if(left_head->val < right_head->val){
                prev->next = left_head;
                left_head = left_head->next;
                prev = prev->next;
            }else{
                prev->next = right_head;
                right_head = right_head->next;
                prev = prev->next;


        }
        //剩余部分合并
        while(left_head != NULL){
            prev->next = left_head;
            left_head = left_head->next;
            prev = prev->next;
        }


        while(right_head != NULL){
            prev->next = right_head;
            right_head = right_head->next;
            prev = prev->next;
        }


        return dummy.next;
    }
};


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

单链表排序(插入与归并)

标签:单链表   插入排序   归并排序   

原文地址:http://blog.csdn.net/tangchenchan/article/details/47210935

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