/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { if(pHead1 == NULL && pHead2 == NULL) return {}; if(pHead1 == NULL) return pHead2; if(pHead2 == NULL) return pHead1; //以上特殊情况判断 int min; //min找到两个链表的第一个谁小 if(pHead1->val < pHead2->val){ min = pHead1->val; pHead1 = pHead1->next; //指针要指向下一个 } else{ min = pHead2->val; pHead2 = pHead2->next; } ListNode* res = new ListNode(min); //利用min创建一个返回的链表 ListNode* rec = res; //头节点记录,方便返回 while(1){ if(pHead1 == NULL && pHead2 == NULL) break; //退出循环 if(pHead1 == NULL){ res->next = pHead2; //一个表走完了,直接指向另一个表退出 break; } if(pHead2 == NULL){ res->next = pHead1; break; } if(pHead1->val < pHead2->val){ res->next = pHead1; //找出小的那个,指向该节点 res = res->next; //res更新 pHead1 = pHead1->next; //这个节点的指针去下一个 res->next = NULL; //把这个节点从原链表摘出来 } else{ res->next = pHead2; res = res->next; pHead2 = pHead2->next; res->next = NULL; //把这个节点从原链表摘出来 } } return rec; } };