Merge k Sorted Lists [LeetCode]

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

Summary:  Finds the smallest node every round, then links it to the one sorted list.

 1     ListNode *mergeKLists(vector<ListNode *> &lists) {
 2         ListNode * head = NULL;
 3         ListNode * pre_node = NULL;
 4         while(true){
 5             //find the smallest one
 6             ListNode * smallest_node = NULL;
 7             for(auto item : lists) {
 8                 if(item != NULL){
 9                     if(smallest_node == NULL || item->val < smallest_node->val )
10                         smallest_node = item;
11                 }
12             }
13             if(smallest_node == NULL)
14                 break;
15                 
16             if(pre_node == NULL){
17                 pre_node = smallest_node;
18                 head = pre_node;
19             }else{
20                 pre_node -> next = smallest_node;
21                 pre_node = pre_node -> next;
22             }
23             
24             for(int i = 0; i< lists.size(); i ++){
25                 if(lists[i] == smallest_node)
26                     lists[i] = lists[i] -> next;
27             }
28         }
29         return head;
30     }

 

转载于:https://www.cnblogs.com/guyufei/p/3410366.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值