104. Merge K Sorted Lists

104. Merge K Sorted Lists

Description:

Merge k sorted linked lists and return it as one sorted list.

Analyze and describe its complexity.

Example
Example 1:
Input: [2->4->null,null,-1->null]
Output: -1->2->4->null

Example 2:
Input: [2->6->null,5->null,7->null]
Output: 2->5->6->7->null

Main Idea:

It’s the follow-up question of merge two list. Thus, all we need is to iterate the vector n times to merge two lists.

Tips/Notes:
  1. Don’t make mistake when writing merge two list.

Code:

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param lists: a list of ListNode
     * @return: The head of one sorted list.
     */
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // write your code here
        ListNode* dummy = new ListNode(-1);
        ListNode* tmp = dummy;
        for(auto now : lists){
            tmp->next = mergeTwoLists(tmp->next, now);
        }
        
        return dummy->next;
        
    }
    
    ListNode* mergeTwoLists(ListNode * l1, ListNode * l2) {
        // write your code here
        ListNode* dummy = new ListNode(-1);
        ListNode* tmp = dummy;
        while(l1 || l2){
            if(l1 == nullptr){
                tmp->next = l2;
                return dummy->next;
            }
            if(l2 == nullptr){
                tmp->next = l1;
                return dummy->next;
            }
            
            if(l1->val <= l2->val){
                tmp->next = l1;
                tmp = tmp->next;
                l1 = l1->next;
            }
            else{
                tmp->next = l2;
                tmp = tmp->next;
                l2 = l2->next;
            }
        }
        return dummy->next;
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值