leetcode 148. 排序链表

leetcode 148. 排序链表_第1张图片

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeSort(ListNode* head)
    {
        if(head->next == NULL) return head;
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast->next !=NULL && fast->next->next !=NULL)
        {
            fast=fast->next->next;
            slow=slow->next;
        }
        ListNode* r=slow->next;
        slow->next=NULL;
        ListNode* left = mergeSort(head);
        ListNode* right = mergeSort(r);
        ListNode* tmp1=new ListNode(-1);
        ListNode* tmp=tmp1;
        while(left != NULL || right != NULL)
        {
            if(left == NULL && right != NULL) 
            {
                tmp->next = right;
                right = right->next;
                tmp = tmp->next;
                tmp->next = NULL;
            }
            else if(left != NULL && right == NULL)
            {
                tmp->next = left;
                left = left->next;
                tmp = tmp->next;
                tmp->next = NULL;
            }
            else if(left->val < right->val)
            {
                tmp->next = left;
                left = left->next;
                tmp = tmp->next;
                tmp->next = NULL;
            }
            else 
            {
                tmp->next = right;
                right = right->next;
                tmp = tmp->next;
                tmp->next = NULL;
            }
        }
        return tmp1->next;
    }
    ListNode* sortList(ListNode* head) {
        if(head == NULL || head->next == NULL) return head;
        return mergeSort(head);
    }
};

 

你可能感兴趣的:(Leetcode,复习)