力扣两数想加

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
//初始化头和尾(yǐ)巴
struct ListNode*head=NULL;
struct ListNode*end=NULL;
//定义一个增加节点的函数
void addlist(int a)
{
    struct ListNode*ptemp=(struct ListNode*)malloc(sizeof(struct ListNode));
    ptemp->val=a;
    ptemp->next=NULL;
    if(head==NULL||end==NULL)
    {
        head=ptemp;
        end=ptemp;
    }
    else
    {
        end->next=ptemp;
        end=ptemp;
    }
}
void freelist()
{
    struct ListNode*ptemp=head;
    while(ptemp!=NULL)
    {
        struct ListNode*pt=ptemp;
        ptemp=ptemp->next;
        free(pt);
    }
    head=NULL;
    end=NULL;
}
//思路就是吧这个挨个提出来
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
    freelist();
struct ListNode*pt1=l1;
struct ListNode*pt2=l2;
int a=0;
int b=0;
int c=0;

while(pt1!=NULL||pt2!=NULL)
{
    if(pt1!=NULL&&pt2!=NULL)
    {
        a=pt1->val;
        b=pt2->val;
        if(c==0)
        {
         if(a+b<10){

         addlist(a+b);
         c=0;
         }
         else if (a+b>=10)
         {
         addlist((a+b)%10);
         c=1;
         }
        }
        else if(c==1)
        {
            if(a+b+c<10){
            addlist(a+b+c);
            c=0;
            }
            else if(a+b+c>=10)
            {
                addlist((a+b+c)%10);
                c=1;
            }
        }
        pt1=pt1->next;
        pt2=pt2->next;
        
    }
    else if (pt1!=NULL&&pt2==NULL)
    {
        a=pt1->val;
        if(a+c<10){
        addlist(a+c);
        c=0;
        }
        else if(a+c>=10)
        {
            addlist((a+c)%10);
            c=1;
        }
        pt1=pt1->next;
    }
    else if(pt2!=NULL&&pt1==NULL)
    {
        b=pt2->val;
        if(b+c<10)
        {
            addlist(b+c);
            c=0;
        }
        else if(b+c>=10)
        {
            addlist((b+c)%10);
            c=1;
        }
        pt2=pt2->next;
    }
    
}
if(c==1)
{
    addlist(1);
    return head;
}
return head;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值