题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <cstdio>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类vector
* @return ListNode类
*/
ListNode* mergeKLists(vector<ListNode*>& lists) {
// write code here
if (lists.empty()) {
return nullptr;
}
if (lists.size() == 1) {
return lists.front();
}
ListNode* head = lists[0];
for (int i = 1; i < lists.size(); i++) {
head = Merge(head, lists[i]);
}
return head;
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
// 其中一个为空,直接返回另一个
if (pHead1 == nullptr) {
return pHead2;
} else if (pHead2 == nullptr) {
return pHead1;
}
// 以链表一为基链表,设置头节点,将链表二插入到链表一中
ListNode* preHead = new ListNode(-1000);
preHead->next = pHead1;
// 三个指针
ListNode* insertPre = preHead; // 指向被插入位置pre节点
ListNode* insertNxt = pHead1; // 指向被插入位置next节点
ListNode* insert = pHead2; // 指向待插节点
while (pHead1 != nullptr && pHead2 != nullptr) {
// 遍历pHead1链表,找到第一个val大于pHead2->val的节点
while (insertNxt != nullptr && insert->val > insertNxt->val) {
insertPre = insertPre->next;
insertNxt = insertNxt->next;
}
// 将phead2中所有节点值小于等于insertNxt->val的节点,前插
while (insert != nullptr && insertNxt != nullptr &&
insert->val <= insertNxt->val) {
// 保存指针
pHead2 = pHead2->next;
// 插入
insert->next = insertNxt;
insertPre->next = insert;
// 更新指针
insertPre = insert;
insert = pHead2;
}
// 如果链表1此时已经没有后续节点, 直接将链表2链接到1后面
if (insertNxt == nullptr) {
insertPre->next = pHead2;
return preHead->next;
}
pHead1 = insertNxt;
}// end while
return preHead->next;
} //
};
360集团公司氛围 358人发布
查看17道真题和解析