刷题-力扣-148. 排序链表

148. 排序链表

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。

进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

示例 1:

输入:head = [4,2,1,3]
输出:[1,2,3,4]

示例 2:

输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]

示例 3:

输入:head = []
输出:[]

提示:

  • 链表中节点的数目在范围 [0, 5 * 104] 内
  • -105 <= Node.val <= 105

题目分析

  1. 根据题目描述对链表排序
  2. 把链表的每个结点存储下为vector nodeList,定义sort中的compare函数,进行排序
  3. 把排序好的nodeList连接起来

代码

/**
 * 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 || !(head->next)) return head;
        vector<ListNode*> nodeList;
        while (head) {
            nodeList.push_back(head);
            head = head->next;
        }
        sort(nodeList.begin(), nodeList.end(), compare);
        for (int i = 0; i < nodeList.size() - 1; ++i) {
            nodeList[i]->next = nodeList[i + 1];
        }
        nodeList[nodeList.size() - 1]->next = nullptr;
        return nodeList[0];
    }

    bool static compare(ListNode* a, ListNode* b) {
        return a->val < b->val;
    }
};
原文地址:https://www.cnblogs.com/HanYG/p/14860386.html