//例1:
//输入:
{1,3,5},{2,4,6}
//返回值:
{1,2,3,4,5,6}
//============
//例2:
//输入:
{},{}
//返回值:
{}
//例3:
//输入:
{-1,2,4},{1,3,4}
//返回值:
{-1,1,2,3,4,4}
/**
* 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* vhead = (struct ListNode*)malloc(sizeof(struct ListNode)); //新建一个头结点
vhead->val = -1;
struct ListNode *p = vhead; //用一个指针指向该头结点
while (pHead1 && pHead2) //两个链表都未比较完
{
if (pHead1->val <= pHead2->val) //表1的值更小
{
p->next = pHead1; //先将结点连接到新表,再让原表指针后移一位,二者顺序不可换
pHead1 = pHead1->next;
}
else {
p->next = pHead2;
pHead2 = pHead2->next;
}
p = p->next; //加入一个新结点后,新表指针也后移一位
}
p->next = pHead1 ? pHead1 : pHead2; //都比较完后,哪个表非空则直接加入到新表中
return vhead->next; //返回第一个结点
}