题目如下
思路和代码
输出是一个链表,我创建的这个链表,在赋值的过程中,表头会改变,所以要记录下最初的表头,这就是不忘初心,方得始终呀!
p->next赋值就比较两个链表的大小就可以了
/*
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&&!pHead2) return NULL;
ListNode* p= new ListNode(0);
ListNode* head=p;
while(pHead1&&pHead2){
if(pHead1->val>=pHead2->val){
p->next=pHead2;
p=p->next;
pHead2 = pHead2->next;
}else{
p->next=pHead1;
p=p->next;
pHead1 = pHead1->next;
}
}
if(pHead1){
p->next=pHead1;
}
if(pHead2){
p->next=pHead2;
}
return head->next;
}
};