单链表中的数相加

你有两个由单链表表示的数。每个结点代表其中的一位数字。数字的存储是逆序的,也就是说个位位于链表的表头。写一函数使这两个数相加并返回结果,结果也由链表表示。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值