题解 | #合并两个排序的链表#
合并两个排序的链表
https://www.nowcoder.com/practice/d8b6b4358f774294a89de2a6ac4d9337
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
#include <stdlib.h>
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode* vhead =(struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* p=vhead;//p先指向头结点
while(pHead1&&pHead2){//都不为NULL才能循环比较
if(pHead1->val<pHead2->val)
{
p->next=pHead1;
pHead1=pHead1->next;
}
else {
p->next=pHead2;
pHead2=pHead2->next;
}
p=p->next;//加入一个新的节点,新表的指针也后移一位
}
if(pHead1)
p->next=pHead1;
else
p->next=pHead2;
// p->next = pHead1 ? pHead1 : pHead2; //都比较完后,哪个表非空则直接加入到新表中
return vhead->next;//返回头结点
}

查看9道真题和解析