148. Sort List 链表归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
void mergeLink(ListNode* head,ListNode* mid, ListNode* last){
    ListNode* head1=head;
    ListNode* end1 = mid;
    ListNode* rehead2 = mid->next;//记录第一个链表的结尾
    ListNode* head2 = mid->next,*end2 = last;
    ListNode* temp1,*temp2;
    while(head1->next!=rehead2){
        while(head1->next!=rehead2 && head1->next->val<=head2->val){//当第一个链表小雨第二个链表就一直遍历
            head1=head1->next;
        }
        if(head1->next == rehead2){//当第一个链表到尾了直接把第二个链表接到第一个链表上
            head1->next = head2;
            break;
        }else{
            temp2 = head2->next;
            temp1 = head1->next;
            head1->next = head2;
            head2->next = temp1;
            head2 = temp2;
            head1=head1->next;
            if(head2 == end2){//当第二个链表到尾了,找到第一个链表的尾然后把第二个链表的尾接到第一个链表的尾
                while(head1->next!=rehead2) head1 = head1->next;
                head1->next = head2;
                break;
            }
        }
    }
} 
void mergesort(ListNode* head,ListNode* last){
    ListNode* fast = head,*slow = head;
    if(head->next == last || head->next->next==last) return;
    while(fast!=last && fast->next!=last){//寻找中位数
        fast=fast->next->next;
        slow = slow->next;
    }
    mergesort(head,slow->next);
    mergesort(slow,last);
    mergeLink(head,slow,last);//合并两个链表
    return;
}
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head==NULL || head->next == NULL) return head;
        ListNode* newHead = new ListNode(0);
        newHead->next = head;
        mergesort(newHead,nullptr);
        return newHead->next;
    }
};


你可能感兴趣的:(链表)