/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
// 获取两个节点中较大的节点
ListNode* getMin(ListNode* node1, ListNode* node2) {
return node1->val > node2->val ? node2 : node1;
}
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// 空处理
if (pHead1 == nullptr) {
return pHead2;
}
if (pHead2 == nullptr) {
return pHead1;
}
// 新建用于管理新链的头节点
ListNode newNode(0);
ListNode* it1 = pHead1;
ListNode* it2 = pHead2;
ListNode* it3 = &newNode;
// 在循环内处理退出
while (1) {
// 若it1为空则直接将it2接入新链表
if (it1 == nullptr) {
it3->next = it2;
break;
}
// 同理it1接入新链表
if (it2 == nullptr) {
it3->next = it1;
break;
}
// 若都不为空责将val值较大的接入
it3->next = getMin(it1, it2);
it3 = it3->next;
// 接入谁谁移动
if (it3 == it1) {
it1 = it1->next;
}
if (it3 == it2) {
it2 = it2->next;
}
}
return newNode.next;
}
};