已知要合并的两个链表是递增的排列,合并为新链表时我们可以考虑建立伪头部
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
*
* @param pHead1 ListNode类
* @param pHead2 ListNode类
* @return ListNode类
*/
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
// write code here
struct ListNode dummy; //声明伪头指针
struct ListNode * cur=&dummy; //cur即为伪头指针
while(pHead1&&pHead2){ //只要两链表不为空 ,开始查找
if(pHead1->val<=pHead2->val){ //当pHead1的值小于pHead2,将其链接到新链表后
cur->next=pHead1;
pHead1=pHead1->next; //然后后移链表1
}
else
{
cur->next=pHead2;
pHead2=pHead2->next; //同上反之
}
cur=cur->next;
}
cur->next=pHead1==NULL?pHead2:pHead1; //链表判空,若1空则链接2,反之链接1,采用宏判断
return dummy.next; 返回新链表的头部
}