【问题描述】给定两个用链表表示的整数,每个节点包含一个数位。这些数位是反向存放的,也就是个位排在链表首部。编写函数对这两个整数求和,并用链表形式返回结果。输入:(7 -> 1 -> 6) +

【问题描述】

给定两个用链表表示的整数,每个节点包含一个数位。这些数位是反向存放的,也就是个位排在链表首部。编写函数对这两个整数求和,并用链表形式返回结果。

输入:(7 -> 1 -> 6) + (5 -> 9 -> 2),即617 + 295

输出:2 -> 1 -> 9,即912

【输入形式】

第一行输入第1个整数(逆序);

第二行输入第2个整数(逆序);

每个数位以空格分隔。

【输出形式】

输出和的逆序。

【样例输入】

7 1 6 e

5 9 2 e

【样例输出】

2 1 9

【样例说明】

样例中的e,表示输入以非法整数作为输入结束;

两个整数的位数不一定相同,即有可能1+11111

也可能会出现,某个整数不存在的情况(即链表为空链的情况)

【评分标准】

不允许修改程序其他结构,只补充加法函数。

#include<stdio.h>
#include<stdlib.h>

typedef  int ElemType;
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}LNode,*LinkList;

LinkList initList()
{
    LinkList head;
    head=(LinkList)malloc(sizeof(LNode));
    if(head==NULL)
    {
        return NULL;
    }
    head->next=NULL;
    return head;
}
//在链表末尾插入结点,并返回尾指针
LinkList insertListTail(LinkList tail, ElemType e)
{
    LinkList s;
    if(tail==NULL)
    {
        return 0;
    }
    s=(LinkList)malloc(sizeof(LNode));
    if(s==NULL)
    {
        return 0;
    }
    s->data=e;
    s->next=tail->next;
    tail->next=s;
    tail=s;
    return tail;
}
void printList(LinkList head)
{
    LinkList p=head->next;
    while(p)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}
//函数返回结果链表
LinkList addList(LinkList ha,LinkList hb)
{
    LinkList hc,tc,a,b;//tc是新链表的尾部,hc是头部,和倒叙插入这个新链表
    hc=tc=initList();
    int sum,x,y;
    a=ha->next;
    b=hb->next;
    sum=x=y=0;
    while(a&&b)//a和b都没结束的时候
    {
        sum=a->data+b->data+x;
        x=sum/10;//进位
        y=sum%10;//当前位置
        tc=insertListTail(tc,y);
        a=a->next;
        b=b->next;
    }
    while(a)
    {
        sum=a->data+x;
        x=sum/10;
        y=sum%10;
        tc=insertListTail(tc,y);
        a=a->next;
    }
    while(b)
    {
        sum=b->data+x;
        x=sum/10;
        y=sum%10;
        tc=insertListTail(tc,y);
        b=b->next;
    }
    if(x>0)
        tc=insertListTail(tc,x);
        return hc;

}
int main()
{
    LinkList ha,ta,hb,tb,hc;
    ElemType e;
    ta=ha=initList();
    tb=hb=initList();
    while(scanf("%d",&e)==1){
        ta=insertListTail(ta,e);
    }
    getchar();
    while(scanf("%d",&e)==1){
        tb=insertListTail(tb,e);
    }
   // printList(ha);
   // printList(hb);
    hc=addList(ha,hb);
    printList(hc);
    return 0;
}
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值