You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
std::vector<int> num1, num2; //存储数字1,2
int num_count1(0), num_count2(0); //数字数组1和2中数字的个数
//获得链表1对应的数字
ListNode* temp_node = l1;
while(NULL != temp_node)
{
num1.push_back(temp_node->val);
temp_node = temp_node->next;
}
num_count1 = num1.size();
//获得链表2对应的数字
temp_node = l2;
while(NULL != temp_node)
{
num2.push_back(temp_node->val);
temp_node = temp_node->next;
}
num_count2 = num2.size();
//两个数字数组相加
if(num_count1 > num_count2)
{
for(int i=num_count2; i<num_count1; i++)
{
num2.push_back(0);
}
}
else if(num_count1 < num_count2)
{
for(int i=num_count1; i<num_count2; i++)
{
num1.push_back(0);
}
}
//两个数字相加且分割
std::vector<int> num3; //两个数字相加得到的结果数组
int num_count = num1.size();
bool flag = false; //数字相加进位标志
for(int i=0; i<num_count; i++)
{
int temp = num1[i] + num2[i];
if(flag)
{
temp++;
flag = false;
}
if(temp > 9)
{
temp -= 10;
flag = true;
}
num3.push_back(temp);
}
if(flag)
num3.push_back(1);
ListNode* return_node = new ListNode(0);
temp_node = return_node;
/*
if(num_count >= 10)
{
num3.push_back(data1+data2);
num3.push_back(data1);
num3.push_back(data2);
for(int i=0; i<num2.size(); i++)
num3.push_back(num2[i]);
}
*/
num_count = num3.size();
if(num_count > 0)
{
return_node->val = num3[0];
if(num_count > 1)
{
for(int i=1; i<num_count; i++)
{
ListNode* temp = new ListNode(num3[i]);
return_node->next = temp;
return_node = return_node->next;
}
}
}
return temp_node;
}
};