链表相加

来源:互联网 发布:外国人万能的淘宝 编辑:程序博客网 时间:2024/05/23 13:17

    给定两个链表,分别表示两个非负整数。他们的数字逆序存储在链表中,且每个节点只存储一个数字,计算两个数的和,并且返回和的链表头指正。

如:输入1->2>3 8->7->7 输出:0->0->0->1

   解法:因为两个数都是逆序存储,正好可以从头向后依次想加,完成加法运算。注意考虑尾数不同的情况。

   扩展:可以实现大整数运算!

#include<cstdio>#include<iostream>#include<string>#include<malloc.h>using namespace std; struct node{int val;node *next;node(int v):val(v),next(NULL){}};int n,m;void print(node *hea){node *p=hea->next;int f=0;while(p){if(f)printf(" ");printf("%d",p->val);f=1;p=p->next;}}void adds(node *hea1,node *hea2){node *p=hea1,*q=hea2,*tail,*tmp;tail=new node(0);int car=0,s;if(n>m){q=hea1;p=hea2;}while(p&&q){s=p->val+q->val+car;car=s/10;s=s%10;q->val=s;tmp=new node(s);tail->next=tmp;//尾插法tail=tmp;p=p->next;q=q->next;}while(q){s=q->val+car;car=s/10;s%=10;q->val=s;q=q->next;}if(n>m)print(hea1);elseprint(hea2);if(car)printf(" 1\n");//把最后的进位加上elseprintf("\n");}int main(){while(scanf("%d%d",&n,&m)!=EOF){node *hea1,*hea2,*p;int num;hea1=new node(0);hea2=new node(0);for(int i=0;i<n;i++){scanf("%d",&num);p=new node(num);p->next=hea1->next;hea1->next=p;}for(i=0;i<m;i++){scanf("%d",&num);p=new node(num);p->next=hea2->next;//头插法hea2->next=p;}adds(hea1,hea2);}return 0;}


 

0 0
原创粉丝点击