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
Answer:
/**
* 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) {
bool m_shouldIncrese = false;
ListNode *m_temp_l1 = l1;
ListNode *m_temp_l2 = l2;
int m_l1_length = 0;
int m_l2_length = 0;
do{
m_l1_length++;
m_temp_l1 = m_temp_l1->next;
}while(m_temp_l1 != NULL);
do {
m_l2_length++;
m_temp_l2 = m_temp_l2->next;
}while(m_temp_l2 != NULL);
ListNode *m_small;
ListNode *m_large;
if (m_l1_length < m_l2_length){
m_small = l1;
m_large = l2;
}
else{
m_large = l1;
m_small = l2;
}
ListNode *temp = new ListNode(0);
ListNode *result = temp;
do{
int sum = 0;
if(m_small != NULL)
{
sum = m_large->val + m_small->val + temp->val;
}
else{
sum = m_large->val + temp->val;
}
int val = -1;
if(sum >= 10){
val = sum - 10;
m_shouldIncrese = true;
}
else{
val = sum;
m_shouldIncrese = false;
}
temp->val = val;
m_large = m_large->next;
if(m_small != NULL)
{
m_small = m_small->next;
}
if(m_large != NULL || m_shouldIncrese){
temp->next = new ListNode(0);
temp = temp->next;
if (m_shouldIncrese)
{
temp->val = 1;
}
}
}while(m_large != NULL);
return result;
}
};
网友评论