LeetCode 148 Sort List

标签: LeetCode 发布于:2022-03-02 16:57:33 编辑于:2022-03-02 16:57:33 浏览量:838

概述

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

暴力法

直接取出每个节点进行排序,之后拼起来。

实现的时候注意给最后一个节点的 next 指针置 nullptr。

class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if (!head) return nullptr;
        vector<ListNode*> arr;
        while (head != nullptr) {
            arr.push_back(head);
            head = head->next;
        }
        sort(arr.begin(), arr.end(), [](const auto& a, const auto& b)->bool {
           return a->val < b->val; 
        });
        for (int i = 0; i < arr.size() - 1; i ++) {
            arr[i]->next = arr[i+1];
        }
        arr[arr.size()-1]->next = nullptr;
        return arr[0];
    }
};

未经允许,禁止转载,本文源站链接:https://iamazing.cn/