LeetCode OJ Merge k Sorted Lists

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        if (lists.size() == 0) return NULL;
        if (lists.size() == 1) return lists[0];
        ListNode *new_head = NULL;
        ListNode *move;
        bool is_head = true;  // weather to make the head of the return list
        while (1) {
            bool is_empty = true;  // to see if it's empty(all NULL)
            int min;
            int mem;
            int i;
            int j;
            for (i = 0; i < lists.size(); i++) {  // find the first val
                if (lists[i] != NULL) {
                    is_empty = false;
                    min = lists[i]->val;
                    mem = i;
                    break;
                }
            }
            if (is_empty) {  // notice that lists may be {NULL, NULL}, so the initial value of new_head is NULL
                return new_head;
            }
            for (j = i + 1; j < lists.size(); j++) {  // find the min val and the pos
                if (lists[j] && lists[j]->val < min) {
                    min = lists[j]->val;
                    mem = j;
                }
            }
            if (is_head) {
                is_head = false;
                new_head = new ListNode(min);
                move = new_head;
            } else {
                ListNode *new_node = new ListNode(min);
                move->next = new_node;
                move = move->next;
            }
            ListNode *del = lists[mem];
            lists[mem] = lists[mem]->next;
            delete del;
        }
    }
};

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值