首页 > 代码库 > LeetCode Merge K Sorted Lists
LeetCode Merge K Sorted Lists
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; } };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。