力扣链表练习2-合并两个有序表

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;
        }
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值