class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2) { ListNode* head=new ListNode(0);//创建合成链表 ListNode* cur=head; if(pHead1==NULL) return pHead2; if(pHead2==NULL) return pHead1; while(pHead1&&pHead2) { if(pHead1->val<=pHead2->val) { cur->next=pHead1; pHead1=pHead1->next; cur=cur->next; } else { cur->next=pHead2; pHead2=pHead2->next; cur=cur->next; } } //讨论到底情况 if(pHead1) cur->next=pHead1; else cur->next=pHead2; return head->next; } };
合并两个有序链表:
1.核心:“两权,选择,移动”(包括边指针pHead和主指针cur的移动)
2.注意对到底情况的讨论,将剩下的链表直接加入主体中。
3.因为单链表指针到底后无法回转的事实,需要我们在一次遍历中完成任务,这道题的模式有点像蜘蛛。