/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
struct ListNode head1Node = { .next = pHead1 };
struct ListNode head2Node = { .next = pHead2 };
struct ListNode* p1 = pHead1;
struct ListNode* p1Pre = &head1Node; // p1的前元素
struct ListNode* p2 = pHead2;
if ((pHead1 == NULL) && (pHead2 != NULL)) {
return pHead2;
} else if ((pHead1 != NULL) && (pHead2 == NULL)) {
return pHead1;
} else if ((pHead1 == NULL) && (pHead2 == NULL)) {
return NULL;
}
while ((p1 != NULL) && (p2 != NULL)) {
if (p1->val >= p2->val) {
//将p2元素插入p1前
head2Node.next = p2->next;
p2->next = p1;
p1Pre->next = p2;
p1Pre = p1Pre->next;
p2 = head2Node.next;
} else {
//移动p1和p1Pre
p1 = p1->next;
p1Pre = p1Pre->next;
}
}
//如果list1已经遍历结束,则说明剩下的list2均大于list1,直接接在list1尾部即可
if (p1 == NULL) {
p1Pre->next = p2;
}
return head1Node.next;
}