链表排序c++

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* sortList(ListNode* head) {
        vector<int> xx;
        ListNode *temp = head;
        while(temp)
        {
            xx.push_back(temp->val);
            temp = temp->next;
        }
        sort(xx.begin(),xx.end());
        temp = head;
        int i = 0;
        while(temp)
        {
            temp->val = xx[i];
            temp = temp->next;
            i++;
        }
        return head;
    }
};

思路2:自己实现归并排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *sortList(ListNode *head) {
        if (head == NULL || head->next == NULL)
            return head;
        //利用快慢指针将链表分成两部分
        ListNode *fast = head, *slow = head;
        while (fast->next != NULL && fast->next->next != NULL) 
        {
            fast = fast->next->next;
            slow = slow->next;
        }
        fast = slow;
        slow = slow->next;
        fast->next = NULL;
        ListNode *l1 = sortList(head);
        ListNode *l2 = sortList(slow);
        return mergeTwoLists(l1, l2);
    }
        //将两个链表连起来
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode dummy(-1);
        for (ListNode* p = &dummy; l1 != nullptr || l2 != nullptr; p = p->next) 
        {
            int val1 = l1 == nullptr ? INT_MAX : l1->val;
            int val2 = l2 == nullptr ? INT_MAX : l2->val;
            if (val1 <= val2) 
            {
                p->next = l1;
                l1 = l1->next;
            } 
            else 
            {
                p->next = l2;
                l2 = l2->next;
            }
        }
        return dummy.next;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_23905237/article/details/88143325