lc 排序链表

链接: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 到数组中排序然后再重新返回到链表。也可递归,现在写

posted on 2020-05-24 23:34  FriskyPuppy  阅读(159)  评论(0编辑  收藏  举报

导航