力扣 148. 排序链表

74 阅读1分钟

🔗 leetcode.cn/problems/so…

题目

  • 返回排序后的链表

思路

  • 复制出来之后用了 stl 的 sort,再把值复制回去

代码

/**
 * 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) {
        vector<int> vec;
        ListNode* curr = head;
        while (curr) {
            vec.push_back(curr->val);
            curr = curr->next;
        }
        sort(vec.begin(), vec.end());
        curr = head;
        for (auto item : vec) {
            curr->val = item;
            curr = curr->next;
        }
        return head;
    }
};