LeetCode刷题(C++)——Merge k Sorted Lists(Hard)

来源:互联网 发布:杀网络喷子的动漫 编辑:程序博客网 时间:2024/06/01 15:53

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.empty())return NULL;ListNode* newlist = NULL;for (int i = 0; i < lists.size();i++){newlist = mergeKLists(newlist, lists[i]);}return newlist;}ListNode* mergeKLists(ListNode* list1, ListNode* list2) {if (list1 == NULL&&list2 == NULL)return NULL;if (list1 == NULL)return list2;if (list2 == NULL)return list1;ListNode* newlist = new ListNode(-1);ListNode* p = newlist;while (list1 != NULL&&list2 != NULL){if (list1->val < list2->val){p->next = list1;p = list1;list1 = list1->next;}else{p->next = list2;p = list2;list2 = list2->next;}}if (list1 != NULL)p->next = list1;if (list2 != NULL)p->next = list2;return newlist->next;    }};


0 0
原创粉丝点击