【c++】148. 排序链表

1.题目

https://leetcode.cn/problems/sort-list/

2.解法

递归排序+递归合并链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (head == NULL || head->next == NULL)
        {
            return head;
        }
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* prev = NULL;

        while (fast != NULL && fast->next != NULL)
        {
            prev = slow;
            fast = fast->next->next;
            slow = slow->next;
        }
        ListNode* newhead = slow;
        prev->next = NULL;
        
        ListNode* l1 = sortList(head);
        ListNode* l2 = sortList(newhead);

        return merge(l1, l2);
    }

    ListNode* merge(ListNode* l1, ListNode* l2)
    {
        ListNode* ls;
        
        if (l1 != NULL && l2 != NULL)
        {
            if (l1->val < l2->val)
            {
                ls = l1;
                ls->next = merge(l1->next, l2);
            } else {
                ls = l2;
                ls->next = merge(l1, l2->next);
            }
        }
        else if (l1 != NULL)
        {
            ls = l1;
        }
        else if (l2 != NULL)
        {
            ls = l2;
        }
        return ls;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_35975447/article/details/128841015