#include <iostream>
#include <cstdlib>
#include <time.h>
#include <iomanip>
#include <string.h>
using namespace std;
#define NUMBER 10
/
//数据结构定义
typedef struct node{
int data;
struct node *next;
}Inode,*Linklist;
/
//头插法存数,低位在前,高位在后
void create_L(Linklist &L)
{
int n,i;
string s;
cin>>s; //输入字符串
Linklist newnode;
L=new node;
L->next=NULL;
if(L==NULL)
cout<<"Failure!";
else
{
i=0;
while(i<s.length())
{
newnode=new node;
newnode->data=s[i]-'0'; //转化成数字
newnode->next=L->next;
L->next=newnode;
i++;
}//for
}//else
}
void add_L(Linklist &L,Linklist &S,Linklist &H)
{
Linklist p,q,n;
int t,r=0;
p=L->next;
q=S->next;
H=new node;
H->next=NULL;
while(p&&q) //头插法,计算后的数高位在前,低位在后
{
n=new node;
n->data=(p->data+q->data+r)%10; //存入一位数
r=(p->data+q->data+r)/10; //进位
n->next=H->next;
H->next=n;
p=p->next;
q=q->next;
}
while(p) //余下的数加入
{
n=new node;
n->data=(p->data+r)%10; //存入一位数
r=(p->data+r)/10; //进位
n->next=H->next;
H->next=n;
p=p->next;
}
while(q)
{
n=new node;
n->data=(q->data+r)%10; //存入一位数
r=(q->data+r)/10; //进位
n->next=H->next;
H->next=n;
q=q->next;
}
if(r) //最高位有进位,则增加一位
{
n=new node;
n->data=r;
n->next=H->next;
H->next=n;
}
}
//输出
void print_L(Linklist L)
{
Linklist p;
p=L->next;
while(p!=NULL)
{
cout<<p->data;
p=p->next;
}//while
}
//主函数
int main()
{
Linklist L,S,H;
create_L(L);
create_L(S);
add_L(L,S,H);
print_L(H);
return 0;
}
两个任意长度整数相加—链表
最新推荐文章于 2022-11-16 10:14:40 发布