You are given two linked lists representing two non-negative numbers. The digits are stored in reverse
order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
1.使用尾插法
2.考虑进位carry
3.两个链表长度不一致的处理
4.最后carry如果大于0,需要新建一个node.
#include <iostream>
using namespace std;
struct LinkNode{
int data;
LinkNode *next;
LinkNode(int x):data(x),next(NULL){}
};
class Solution{
public:
LinkNode *addTowNum(LinkNode *head1,LinkNode *head2)
{
LinkNode *dummy = new LinkNode(-1);
LinkNode *pre = dummy;
int carry = 0;
if(head1 == NULL && head2 == NULL)
return NULL;
while(head1&&head2)
{
int val = head1->data + head2->data + carry;
carry = val/10;
LinkNode *cur = new LinkNode(val%10);
pre->next = cur;//尾插入
pre = pre->next;
head1 = head1->next;
head2 = head2->next;
}
LinkNode *head_remain = head1?head1:head2;
while(head_remain)
{
int val = head_remain->data + carry;
carry = val/10;
LinkNode *cur = new LinkNode(val%10);
pre->next = cur;
pre = pre->next;
head_remain = head_remain->next;
}
if(carry > 0)
{
LinkNode *cur = new LinkNode(carry);
pre->next = cur;
}
LinkNode *head = dummy->next;
delete dummy;
return head;
}
//创建只有空链表,返回一个dummy节点
LinkNode * createLink()
{
LinkNode *dummy = new LinkNode(-1);
return dummy;
}
LinkNode * initLink(LinkNode *dummy,int array[],int len)
{
if(dummy == NULL || sizeof(array) == 0)
return NULL;
LinkNode *tmp,*head;
tmp = dummy;
//使用的是尾插入法
for(int i=0;i<len;i++)
{
LinkNode *p = new LinkNode(array[i]);
tmp->next=p;
tmp = tmp->next;
}
head = dummy->next;
delete dummy;
return head;
}
void showList(LinkNode *head)
{
while(head)
{
printf("%d ",head->data);
head = head->next;
}
printf("\n");
return;
}
//摧毁链表
void desroyList(LinkNode *head)
{
while(head)
{
LinkNode *tmp = head->next;
delete head;
head = tmp;
}
return;
}
};
void main()
{
Solution sol;
int array1[] = {6,2,5};
int len1 = sizeof(array1)/sizeof(int);
int array2[] = {4,5,6};
int len2 = sizeof(array2)/sizeof(int);
LinkNode *dummy1 = sol.createLink();
LinkNode *head1 = sol.initLink(dummy1,array1,len1);
LinkNode *dummy2 = sol.createLink();
LinkNode *head2 = sol.initLink(dummy2,array2,len2);
LinkNode *head = sol.addTowNum(head1,head2);
sol.showList(head);
sol.desroyList(head1);
sol.desroyList(head2);
sol.desroyList(head);
return;
}