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

合并k个已排序的链表

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* AddList(ListNode *pHead1,ListNode *pHead2)
    {
        ListNode *head = new ListNode(0);
        head ->next = pHead1;
        ListNode *res = head;
        while(pHead1 && pHead2)
        {
            if(pHead1->val <= pHead2->val)
            {
                head ->next = pHead1;
                head = head ->next;
                pHead1 = pHead1->next;
            }
            else
            {
                head ->next = pHead2;
                head = head ->next;
                pHead2 = pHead2->next;
            }
        }
        head->next = pHead1?pHead1:pHead2;
        return res->next;
    
    }
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if(lists.size() == 0)
            return  nullptr;
        for(int i = 1;i<lists.size();++i)
        {
            lists[0] = AddList(lists[0],lists[i]);
        }
        return lists[0];
    }
};

解题思路:结合上一题合并两个有序链表的方法,逐个将各个链表合并到list[0]

全部评论

相关推荐

求个公司要我:接好运
点赞 评论 收藏
分享
美丽的查理斯不讲武德:包kpi的啊,感觉虾皮一点hc都没有
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务