LeetCode 148 链表的归并排序

  • 代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:

    ListNode* merge(ListNode* head1, ListNode* head2){
    
    
        ListNode newhead(-1);

        ListNode* trans = &newhead;
        ListNode* trans1 = head1;
        ListNode* trans2 = head2;

        while(trans1 != nullptr && trans2 != nullptr){
    
    
            if(trans1 ->val < trans2 ->val){
    
    
                trans ->next = trans1;
                trans1 = trans1 ->next;
            }else{
    
    
                trans ->next = trans2;
                trans2 = trans2 ->next;
            }
            trans = trans ->next;
        }

        if(trans1 != nullptr){
    
    
            trans ->next = trans1;
        }
        if(trans2 != nullptr){
    
    
            trans ->next = trans2;
        }

        return newhead.next;
    }

    ListNode* sortList(ListNode* head) {
    
    
        if(head == nullptr || head ->next == nullptr) return head;

        ListNode* slow = head;
        ListNode* fast = head;

        while(fast != nullptr){
    
    
            fast = fast ->next;
            if(fast != nullptr){
    
    
                fast = fast ->next;
            }

            if(fast == nullptr) break;
            
            slow = slow ->next;
        }
        
        ListNode* second = slow ->next;
        slow ->next = nullptr;
        return merge(sortList(head), sortList(second));
    }
};

猜你喜欢

转载自blog.csdn.net/xiaoan08133192/article/details/120269208