构建头节点一定要初始化 (归并排序)的应用
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if(!pHead1) return pHead2;
if(!pHead2) return pHead1;
ListNode* vhead=new ListNode(0);;
ListNode* cur;
if(pHead1->val<=pHead2->val){
vhead->next=pHead1;
pHead1=pHead1->next;
}
else {vhead->next=pHead2;
pHead2=pHead2->next;
}
cur=vhead->next;
while(pHead1||pHead2){
if(!pHead1){
cur->next=pHead2;
break;
}
if(!pHead2){
cur->next=pHead1;
break;
}
if(pHead1->val<=pHead2->val){
cur->next=pHead1;
cur=cur->next;
pHead1=pHead1->next;
}else{
cur->next=pHead2;
cur=cur->next;
pHead2=pHead2->next;
}
}
return vhead->next;
}
};