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
题目属于简单的链表问题,对于简单的题目,那么对于细节肯定是要特别考虑的。
/**
* 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) {
if(NULL == l1 && NULL == l2)
return NULL;
if(NULL == l1)
return l2;
if(NULL == l2)
return l1;
ListNode *head = NULL;
ListNode *tmpNode1 = l1, *tmpNode2 = l2, *LastNode = head;
int residue = 0;
while(tmpNode1 != NULL && tmpNode2 != NULL)
{
int tmpSum = tmpNode1->val + tmpNode2->val + residue;
residue = tmpSum / 10;
tmpNode1->val = tmpSum % 10;
if(head == NULL)
{
head = tmpNode1;
LastNode = head;
}
else
{
LastNode->next = tmpNode1;
LastNode = LastNode->next;
}
tmpNode1 = tmpNode1->next;
tmpNode2 = tmpNode2->next;
}
while(tmpNode1 != NULL)
{
int tmpSum = tmpNode1->val + residue;
tmpNode1->val = tmpSum % 10;
residue = tmpSum / 10;
LastNode->next = tmpNode1;
LastNode = LastNode->next;
tmpNode1 = tmpNode1->next;
}
while(tmpNode2 != NULL)
{
int tmpSum = tmpNode2->val + residue;
tmpNode2->val = tmpSum % 10;
residue = tmpSum / 10;
LastNode->next = tmpNode2;
LastNode = LastNode->next;
tmpNode2 = tmpNode2->next;
}
if(residue > 0)
LastNode->next = new ListNode(residue);
if(NULL != LastNode)
LastNode->next == NULL;
return head;
}
};