2023.9.25
本题要合并k个有序链表,最朴素的方法可以联想到之前做的合并两个有序链表。 用一个for循环遍历lists数组,利用合并两个有序链表的代码,不断合并lists中的链表,最后返回头节点即可。
代码如下:
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {ListNode* dummy = new ListNode();ListNode* cur1 = list1;ListNode* cur2 = list2;ListNode* cur = dummy;while(cur1 && cur2){if(cur1->val < cur2->val){cur->next = cur1;cur = cur->next;cur1 = cur1->next;}else{cur->next = cur2;cur = cur->next;cur2 = cur2->next;}}while(cur1){cur->next = cur1;cur = cur->next;cur1 = cur1->next;}while(cur2){cur->next = cur2;cur = cur->next;cur2 = cur2->next;}return dummy->next;}ListNode* mergeKLists(vector<ListNode*>& lists) {if(lists.size() == 0) return nullptr;if(lists.size() == 1) return lists[0];ListNode* node = mergeTwoLists(lists[0],lists[1]);for(int i=2; i<lists.size(); i++){node = mergeTwoLists(node,lists[i]);}return node;}
};