/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
// 合并两个已排序的链表不需要 k 个链表那样再用优先队列了,
// 直接两个指针分别在两个链表上面遍历就好了
// 这道题也启示我们合并 k 个链表的时候可以两两合并,再两两合并,再两两合并。。。
ListNode dummy(0);
ListNode* tail = &dummy;
while (pHead1 && pHead2) {
if (pHead1->val < pHead2->val) {
tail->next = pHead1;
pHead1 = pHead1->next;
} else {
tail->next = pHead2;
pHead2 = pHead2->next;
}
tail = tail->next;
}
// 一般来说会有一个链表遍历完了另一个链表还剩一些节点没遍历的情况
// 没遍历的那些总是比前面遍历过的节点值要大,直接接到答案的结尾
if (pHead1) {
tail->next = pHead1;
} else {
tail->next = pHead2;
}
return dummy.next;
}
};