两数相加(有进位)

#include<stdio.h>
struct ListNode {
    int val;
    struct ListNode *next;
};
struct ListNode*creat()//建立新链表
{
    struct ListNode*head,*p;
    head=(struct ListNode*)malloc(sizeof(struct ListNode));
    head->next=NULL;
    int x;
    scanf("%d",&x);
    while(x!=0)//当输入0时退出循环
    {
        p=(struct ListNode*)malloc(sizeof(struct ListNode));
        p->val=x;
        p->next=head->next;//头插法
        head->next=p;
        scanf("%d",&x);
    }
    return head;//返回链表
};
void print(struct ListNode *head)//输出链表
{
    struct ListNode *p;
    p=head->next;
    while(p!=NULL)
    {
        printf("%d ",p->val);
        p=p->next;
    }
    printf("\n");
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
//两数相加函数
{
   struct ListNode *head,*r,*p,*p1,*p2;
   head=(struct ListNode*)malloc(sizeof(struct ListNode));//建立新链表
   head->next=NULL;
   r=head;
   p1=l1->next;
   p2=l2->next;
   int c=0,item=0;//c表示每一位的数,item表示进位数
   while(p1!=NULL||p2!=NULL)
  {
    p=(struct ListNode*)malloc(sizeof(struct ListNode));
    p->next=NULL;
    r->next=p;//尾插
    r=p;
    c=p1->val+p2->val+item;
    r->val=c%10;
    item=c/10;//进位数
    p1=p1->next;
    p2=p2->next;
  }
   while(p1)
  {
    p=(struct ListNode*)malloc(sizeof(struct ListNode));
    p->next=NULL;
    r->next=p;
    r=p;
    c=p1->val+item;
    r->val=c%10;
    item=c/10;
    p1=p1->next;
}
while(p2)
{
    p=(struct ListNode*)malloc(sizeof(struct ListNode));
    p->next=NULL;
    r->next=p;
    r=p;
    c=p2->val+item;
    r->val=c%10;
    item=c/10;
    p2=p2->next;
}
if(item!=0)//当最后一位进位数!=0时,申请新节点,并插入
{
    p=(struct ListNode*)malloc(sizeof(struct ListNode));
    p->next=NULL;
    r->next=p;
    r=p;
    r->val=item;
}
return head;
}
int main()
{
    struct ListNode *l1,*l2,*l3;
    l1=creat();
    l2=creat();
    print(l1);
    print(l2);
    l3=addTwoNumbers(l1,l2);
    print(l3);
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值