题解 | #单链表的排序#

单链表的排序

https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

#include <algorithm>
#include <vector>
class Solution {
public:
    /**
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        if (head==nullptr) {
        return head;
        }
        vector<int> num;
        ListNode * temp=head;
        while (temp!=nullptr) {
            num.push_back(temp->val);
            temp=temp->next;
        }
        sort(num.begin(), num.end());
        int i=0;
        ListNode * re=head;
        while (head!=nullptr) {
            head->val=num.at(i);
            head=head->next;
            i++;
        }
        return re;
    }
};

全部评论

相关推荐

2025-11-26 09:37
山西大学 测试工程师
累死的一条狗:学长你电脑闹鬼了
点赞 评论 收藏
分享
2025-12-13 14:51
已编辑
井冈山大学 算法工程师
龙虾x:算法比你强的没有你美,比你美的…..算了已经没有比你美的了
工作两年想退休了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务