用单链表求大整数之和,刚学,写了好久了,但是没对
#include "Head.h"
#define MaxSize 100
#include
using namespace std;
int main()
{
string i,j;
int a[MaxSize],b[MaxSize];
c:cout<<"请输入第一个大整数(<=100位):"<
cin>>i;
int lena=i.size();
if(lena>MaxSize)
{
cout<<"输入数值过大,请输入100位以内数值!"<
goto c;
}
d:cout
cin>>j;
int lenb=j.size();
if(lenb>MaxSize)
{
cout<<"输入数值过大,请输入100位以内数值!"<<endl;
goto d;
}
for(int m=0;m<lena;m++)
a[m]=i[m]-48;
for(int n=0;n<lenb;n++)
b[n]=j[n]-48;
LinkList A(a,lena);
LinkList B(b,lenb);
B.PrintList();
cout<<endl;
A.PrintList();
LinkList C;
Add(A,B,C);
cout<<endl;
C.PrintList();
//C.PrintList(A,B);
return 0;
}
#ifndef HEAD_H_INCLUDED
#define HEAD_H_INCLUDED
class Node
{
public:
int data;
Node *next;
};
class LinkList
{
private :
Node *first;
int length;
public:
LinkList();
LinkList(int a[],int n);
~LinkList();
void PrintList(LinkList A,LinkList B);
void PrintList();
void PrintList(LinkList C);
void Insert(int i,int x);
friend void Add(LinkList A,LinkList B,LinkList &C);
};
#endif // HEAD_H_INCLUDED
#include "Head.h"
#include
using namespace std;
LinkList::LinkList()
{
first=new Node;
first->next=NULL;
}
LinkList::LinkList(int a[],int n)
{
first=new Node;
first->next=NULL;
for(int i=0;i
{
Node *s=new Node;
s->data=a[i];
s->next=first->next;
first->next=s;
}
length=n;
}
LinkList::~LinkList()
{
while(first!=NULL)
{
Node* q=first;
first=first->next;
delete q;
}
}
void LinkList::PrintList(LinkList A,LinkList B)
{
Node* m=A.first->next;
while(m!=NULL)
{
cout<data;
m=m->next;
}
cout<<"+";
Node* n=B.first->next;
while(n!=NULL)
{
cout<data;
n=n->next;
}
cout<<"=";
Node* p=first->next;
while(p!=NULL)
{
cout<data;
p=p->next;
}
}
void LinkList::Insert(int i,int x)
{
Node* p=first;
int counter=0;
while(p!=NULL&&counter
{
p=p->next;
counter++;
}
if(p==NULL)
throw"位置";
else
{
Node* s=new Node;
s->data=x;
s->next=p->next;
p->next=s;
}
}
void LinkList::PrintList(LinkList C)
{
Node* p=C.first->next;
while(p!=NULL)
{
cout<data;
p=p->next;
}
}
void LinkList::PrintList()
{
Node* p=first->next;
while(p!=NULL)
{
cout<data;
p=p->next;
}
}
void Add(LinkList A,LinkList B,LinkList &C)
{
Node* pre=A.first;
Node* p=pre->next;
Node* qre=B.first;
Node* q=qre->next;
Node* Cre=C.first;
Node* c=Cre->next;
int flag=0,sum=0;
while(A.length==B.length)
{
sum=p->data+q->data+flag;
if(sum>=10)
{
c->data=sum-10;
flag=1;
}
else if(sum>=0&&sum
{
c->data=sum;
flag=0;
}
p=p->next;
q=q->next;
c->next=Cre->next;
Cre->next=c;
}
while(A.length>B.length)
{
sum=p->data+flag;
if(sum>=10)
{
c->data=sum-10;
flag=1;
}
else if(sum>=0&&sum
{
c->data=sum;
flag=0;
}
p=p->next;
c->next=Cre->next;
Cre->next=c;
}
while(A.length
{
sum=q->data+flag;
if(sum>=10)
{
c->data=sum-10;
flag=1;
}
else if(sum>=0&&sum
{
c->data=sum;
flag=0;
}
q=q->next;
c->next=Cre->next;
Cre->next=c;
}
if(flag)
{
c->data=1;
c->next=Cre->next;
Cre->next=c;
}
}