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.
这是一个大数加法。有两个链表,每个链表的节点存放的是一个数字,其各位是链表的头节点,最后返回两个链表的和。
//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.
struct LinkNode
{
LinkNode * next;
int value;
}
LinkNode * BigAdd(LinkNode * n1, LinkNode * n2)
{
LinkNode * sum = NULL;
LinkNode * start = sum;
LinkNode * h1 = n1;
LinkNode * h2 = n2;
int pre = 0;
while (h1 != NULL && h2 != NULL)
{
int s = h1->value + h2->value + pre;
LinkNode * n = new LinkNode(s, NULL);
if (s >= 10)
{
n->value = (s) % 10;
pre = s - (s/10) * 10;
}
if (sum == NULL)
{
sum = n;
}
else
sum->next = n;
h1 = h1->next;
h2 = h2->next;
}
LinkNode * h = NULL;
if (h1 != NULL)
h = h1;
else (h2 != NULL)
h = h2;
sum->next = h;
while (pre != 0)
{
int s = pre + h->value;
if (h != NULL)
{
if (s >= 10)
{
h->value = s % 10;
pre = s - (s/10) * 10;
}
}
else
{
LinkNode * n = new LinkNode(pre);
pre = 0;
h = n;
}
h = h->next;
}
return start;
}