注释若看不清建议复制到编译器内看
思路:
step1. 在两个链表均为被完全访问的前提下,比较链表节点的大小,按序插入新链表中
step2. 将未被完全访问的链表挂在新链表尾部
struct ListNode* Merge(struct ListNode* pHead1, struct ListNode* pHead2 ) {
if(!pHead1) return pHead2;
if(!pHead2) return pHead1;
struct ListNode* tmpHead = (struct ListNode*)malloc(sizeof(struct ListNode)); // 临时头节点
tmpHead->next = NULL;// 初始化临时头结点
struct ListNode* pcur = tmpHead;// 实现尾插法需要用到的临时尾指针
struct ListNode* p1 = pHead1,*p2 = pHead2;// p1,p2分别用来摘取链表的节点
while(pHead1 != NULL && pHead2 != NULL)// 两个链表都没有访问结束时
{
if(p1->val<p2->val) // pHead1的节点的值小于pHead2的节点的值
{
pHead1 = pHead1->next; // pHead1指向下一个元素
p1->next = pcur->next; // 尾插入tmpHead链表中
pcur->next = p1;
pcur = p1;// 尾部指针始终指向链表最后一个元素
p1 = pHead1;
}
else // 与上面思路一致
{
pHead2 = pHead2->next; // pHead2指向下一个元素
p2->next = pcur->next; // 插入tmpHead链表中
pcur->next = p2; //
pcur = p2;
p2 = pHead2;
}
}
// 判断是否存在链表未完全访问
// 这里有一点需要注意,用的是 if 而不是 while,
// 因为这是链表,且未完全访问的链表本身有序,只需挂在新链表的后面即可
// 若本题的数据结构是数组,则应使用while,因为需要一个个放到新数组的后面
if(pHead1 != NULL) pcur->next = pHead1;
if(pHead2 != NULL) pcur->next = pHead2;
return tmpHead->next;
}
上述代码,即为本人所思考出的本题答案