码迷,mamicode.com
首页 > 其他好文 > 详细

Sort List && Insertion Sort List (链表排序总结)

时间:2014-08-10 01:40:39      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:style   blog   os   io   for   ar   cti   div   

Sort List

          

Sort a linked list in O(n log n) time using constant space complexity.

 

说明:归并排序: 时间 O(nlogn),空间 O(1). 每次将链表一分为二, 然后再合并。快排(用两个指针)
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 
ListNode* getMid(ListNode *head) {
    ListNode *first, *second, *preFirst;
    preFirst = first = second = head;
    while(second != NULL) {
        preFirst = first;
        first = first->next;
        if(second->next == NULL) break;
        second = second->next->next;
    }
    preFirst->next = NULL;
    return first;
}

void Merge(ListNode *head1, ListNode *head2) {
    if(head1->val > head2->val) {
		int tem = head1->val;
		head1->val = head2->val;
		head2->val = tem;
	}
    ListNode *p = head1;
    while(p->next != NULL && head2 != NULL) {
        if(p->next->val >= head2->val) {
            ListNode *q = p->next;
            p->next = head2;
            head2 = head2->next;
            p->next->next = q;
            p = p->next;
        } else {
            p = p->next;
        }
    }
    if(head2 != NULL)
        p->next = head2;
}
 
void MergeSort(ListNode *head) {
    if(head == NULL || head->next == NULL) return;
    ListNode *mid = getMid(head);
	MergeSort(head);
	MergeSort(mid);
    Merge(head, mid);
}
 
class Solution {
public:
    ListNode *sortList(ListNode *head) {
       MergeSort(head);
       return head;
    }
};

 

Insertion Sort List

          

Sort a linked list using insertion sort.

说明: 与顺序表不同的时,每次找插入位置时从头开始走。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *insertionSortList(ListNode *head) {
        ListNode *p, *q;
        for(q = head; q != NULL; q = q->next) {
            for(p = head; p != q; p = p->next) {
                if(p->val >= q->val) {
                    int tem = p->val;
                    p->val = q->val;
                    q->val = tem;
                }
            }
        }
        return head;
    }
};

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 

Sort List && Insertion Sort List (链表排序总结),布布扣,bubuko.com

Sort List && Insertion Sort List (链表排序总结)

标签:style   blog   os   io   for   ar   cti   div   

原文地址:http://www.cnblogs.com/liyangguang1988/p/3902268.html

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