Cracking The Coding Interview2.4

删除前面的linklist,使用node来表示链表
//	You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
//
//	EXAMPLE
//
//Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
//
//Output: 8 -> 0 -> 8


#include <iostream>
using namespace std;
struct node
{
	int data;
	node *next;
};

void init(node *p,int a[], int size)
{
	if (a==NULL || size<0)
	{
		return;
	}

	for (int i = 0; i < size; i++)
	{
		node *t = new node;
		t->data = a[i];
		p->next = t;
		p = p->next;
	}
	p->next = NULL;
}

void print(node *head)
{
	if (!head)
	{
		return;
	}

	node *p = head->next;

	while (p)
	{
		cout<<p->data<<"  ";
		p = p->next;
	}
	cout<<endl;
}

node * plus(node *a, node *b)
{
	node *pa = a->next;
	node *pb = b->next;
	node *pc = new node;
	node *pi = pc;
	int i = 0;
	int step = 0;
	while(pa!=NULL && pb!= NULL)
	{
		node *t = new node;

		int temp = pa->data + pb->data +step;
		step = 0;
		if (temp >=10)
		{
			temp %= 10;
			step = 1;
		}

		t->data =temp;
		pi->next = t;
		pi = t;
		pa = pa->next;
		pb = pb->next;

	}

	while(pa!= NULL)
	{
		node *t = new node;
		t->data = pa->data + step;
		step = 0;
		pi->next = t;
		pi = t;
		pa = pa->next;	
	}

	while(pb != NULL)
	{
		node *t = new node;
		t->data = pb->data + step;
		step = 0;
		pi->next = t;
		pi = t;
		pb = pa->next;
	}

	if (step>0)
	{
		node *t = new node;
		t->data = step;
		pi->next = t;
		pi = t;
	}
	pi->next = NULL;
	
	return pc;

}

int main()
{
	int a[6] = {1,4,5,9,7,8};
	node *head = new node;
	init(head,a,6);
	print(head);

	int b[6] = {1,4,5,9,7,8};
	node *h = new node;
	init(h,a,6);
	print(h);

	node * r = plus(head, h);
	print(r);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值