码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode Merge K Sorted Lists

时间:2014-06-03 13:26:43      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

bubuko.com,布布扣
class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {   
        ListNode* merged = NULL;
        for (int i=0; i<lists.size(); i++) {
            merged = merge_list(merged, lists[i]);
        }
        return merged;
    }

    // helper function to merge two sorted lists
    ListNode* merge_list(ListNode* l1, ListNode* l2) {
        ListNode* head = NULL;
        ListNode* tail = NULL;
        while (l1 != NULL && l2 != NULL) {
            ListNode* node = NULL;
            if (l1->val <= l2->val) {
                node = l1;
                l1 = l1->next;
            } else {
                node = l2;
                l2 = l2->next;
            }
            if (head == NULL) {
                head = node;
                tail = node;
            } else {
                tail->next = node;
                tail = node;
            }
        }
        if (l1 != NULL) {
            if (head == NULL) {
                head = l1;
            } else {
                tail->next = l1;
            }
        }
        if (l2 != NULL) {
            if (head == NULL) {
                head = l2;
            } else {
                tail->next = l2;
            }
        }
        return head;
    }
};
bubuko.com,布布扣

 

LeetCode Merge K Sorted Lists,布布扣,bubuko.com

LeetCode Merge K Sorted Lists

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/lailailai/p/3759825.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!