题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
    ListNode* mergeTwoLists(ListNode* head1,ListNode* head2) {
        if(head1 == nullptr || head2 == nullptr) return head1 == nullptr ? head2 : head1;
        ListNode* head = head1->val <= head2->val ? head1 : head2;
        ListNode* cur1 = head->next;
        ListNode* cur2 = head == head1 ? head2 : head1;
        ListNode* pre = head;
        while(cur1 && cur2) {
            if(cur1->val <= cur2->val) {
                pre->next = cur1;
                cur1=cur1->next;
            }else{
                pre->next = cur2;
                cur2=cur2->next;
            }
            pre = pre->next;
        }
        pre->next = cur1 ? cur1 : cur2;
        return head;
    }

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.size() == 0) return {};
        if(lists.size() == 1) return lists[0];
        // write code here
        ListNode* head1 = lists[0];
        ListNode* head2 = lists[1];
        ListNode* head = mergeTwoLists(head1,head2);
        for(int i=2;i<lists.size();i++) {
            head = mergeTwoLists(head,lists[i]);
        }
        return head;
    }
};


// [{1,2},{1,4,5},{6}]

// {1,1,2,4,5,6}

// {1,2},{1,4,5}

// {1,1,2,4,5} {6}
// {1,1,2,4,5,6}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-04 14:23
steelhead:你回的有问题,让人感觉你就是来学习的
点赞 评论 收藏
分享
06-20 21:22
已编辑
门头沟学院 Java
纯真的河老师在喝茶:答应了就跑啊,实习随便跑啊,别被pua了,md就是找个廉价劳动力,还平稳过度正式工,到时候跟你说没转正
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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