首页 > 编程语言 > 详细

lc 排序链表

时间:2020-05-25 00:16:53      阅读:56      评论:0      收藏:0      [点我收藏+]

链接:https://leetcode-cn.com/problems/sort-list/

代码:

技术分享图片
/**
 * 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 == nullptr) return nullptr;
        ListNode* cur = head;
        vector<int> v;
        while(cur) {
            v.push_back(cur->val);
            cur = cur->next;
        }
        sort(v.begin(), v.end());
        cur = head;
        for(int i = 0; i < v.size(); i++) {
            cur->val = v[i];
            cur = cur->next;
        }
        return head;
    }
};
View Code

思路:把链表 copy 到数组中排序然后再重新返回到链表。也可递归,现在写

lc 排序链表

原文:https://www.cnblogs.com/FriskyPuppy/p/12953556.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!