题解 | #单链表的排序#

单链表的排序

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

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <algorithm>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param head ListNode类 the head node
     * @return ListNode类
     */
    ListNode* sortInList(ListNode* head) {
        // write code here
        auto Size = [&head](){
            int cnt = 0;
            for(auto cur = head; cur; cur = cur->next) {
                cnt ++;
            }
            return cnt;
        };
        std::vector<int> li;
        li.reserve(Size());

        for(auto cur = head; cur; cur = cur->next) {
            li.emplace_back(cur->val);
        }
        sort(li.begin(), li.end());
        // 如何并行遍历?
        for(auto [vit, lit] = std::make_pair(li.cbegin(), head); lit; ++vit, lit = lit->next) {
            lit->val = *vit;
        }

        return head;
    }
};

全部评论

相关推荐

程序员小白条:主要没亮点,项目也是网上的,平平无奇,那只能海投了,奖项总得有一些,然后就是现在最好是前后端都会,自己能做项目并且运维的,要么找星球项目改改,要么找个开源项目改改,自己能拓展功能才是主要的,跟做效率很低很低
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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