你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的,也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。
#include <iostream>
using namespace std;
typedef struct Node
{
int value;
struct Node *next;
}Node,*pNode;
pNode create_list(int a[], int n)//创建链表
{
if(a==NULL || n<=0)
return NULL;
int i;
pNode head,p,q;
for(i=0;i<n;i++)
{
p = new Node();
p->value = a[i];
p->next = NULL;
if(i==0)
{
head = p;
q = p;
}
else
{
q->next = p;
q = p;
}
}
return head;
}
void print_list(pNode head)//打印链表
{
pNode p = head;
while(p)
{
cout<<p->value<<" ";
p = p->next;
}
}
pNode add_list(pNode head1, pNode head2)//链表相加
{
pNode p = head1,q=head2;
pNode head,prev=NULL;
int carry = 0;//进位
while(p && q)
{
int data = p->value+q->value+carry;
pNode res = new Node();
res->value = data%10;
res->next = NULL;
if(prev)
{
prev->next = res;
prev = res;
}
else
{
head = prev = res;
}
carry = data/10;
p = p->next;
q = q->next;
}
while(p)//p指向的链表长度长
{
int data = p->value + carry;
pNode res = new Node();
res->value = data%10;
res->next = NULL;
prev->next=res;
prev=res;
carry = data/10;
p=p->next;
}
while(q)//q指向的链表长度长
{
int data = q->value + carry;
pNode res = new Node();
res->value = data%10;
res->next = NULL;
prev->next=res;
prev=res;
carry = data/10;
q=q->next;
}
if(carry>0)//如果最后的高位仍然会产生进位,还需创建一个新节点存储它
{
pNode res = new Node();
res->value = carry;
res->next = NULL;
prev->next = res;
}
return head;
}
int main()
{
int a[] = {9,9,9,9};
int n = 4;
int b[] = {9,9,9};
int m = 3;
pNode head1 = create_list(a,n);
pNode head2 = create_list(b,m);
pNode head3 = add_list(head1,head2);
cout<<"被加数从低位到高位依次为:"<<endl;
print_list(head1);
cout<<endl;
cout<<"加数从低位到高位依次为:"<<endl;
print_list(head2);
cout<<endl;
cout<<"结果从低位到高位依次为:"<<endl;
print_list(head3);
cout<<endl;
return 0;
}