struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode*head=NULL,*p=NULL,*Max=NULL;
int a,b;
Max=(struct ListNode*)malloc(sizeof(struct ListNode));
Max->next=NULL;
Max->val=0;
while(list1!=NULL&&list2!=NULL){
a=list1->val;
b=list2->val;
p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->next=NULL;
p->val=a<b?a:b;
if(head==NULL){//判断head是否被赋值
head=p;
Max=p;
}else{
Max->next=p;
Max=p;
}
if(a<b){
list1=list1->next;
}else{
list2=list2->next;
}
}
//让链表剩下的数据录入到Max链表中,上面的操作只是把录完了其中一个链表
while(list1!=NULL){
Max->next=(struct ListNode*)malloc(sizeof(struct ListNode));
Max->next->val=list1->val;
Max=Max->next;
list1=list1->next;
if(head==NULL){//一定要加这个,不加这个的话若有一个链表为空,那他就会输出空表,因为这时head没有被初始化,下面同理
head=Max;
}
}
while(list2!=NULL){
Max->next=(struct ListNode*)malloc(sizeof(struct ListNode));
Max->next->val=list2->val;
Max=Max->next;
list2=list2->next;
if(head==NULL){
head=Max;
}
}
Max->next=NULL;
return head;
}
这样解题代码的篇幅过长,把剩余数据录入链表,其实有更简单的选项,就是将链表直接赋值给Max->next
代码如下
if (list1 != NULL)
{
if (head == NULL)
{
head = list1;
}
else
{
Max->next = list1;
}
}
if (list2 != NULL)
{
if (head == NULL)
{
head = list2;
}
else
{
Max->next = list2;
}
}