题目描述:
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
题目解析:
题目意思是,两个链表相当于一个逆置的数字,将两个链表的相应位置进行相加,最终结果存到一个链表中。注意要有进位。
比如题目中的两个链表:342 + 465 = 807
思路:创建一个新的链表,指向最终结果的链表。当两个链表不为空时,两个链表同时从头开始遍历,用一个变量temp记录遍历到的节点的和,每遍历一个节点,更新一下temp,temp/10,如果有进位,temp就为进位的值,如果没有进位,temp就为0.
AC代码:
/**
* 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(l1 == NULL)
return l2;
if(l2 == NULL)
return l1;
ListNode* head = new ListNode(0);
ListNode* cur = head;
int temp = 0;
while(l1 != NULL || l2 != NULL || temp != 0)
{
if(l1 != NULL)
{
temp += l1->val;
l1 = l1->next;
}
if(l2 != NULL)
{
temp += l2->val;
l2 = l2->next;
}
cur->next = new ListNode(temp % 10);
cur = cur->next;
temp = temp / 10;
}
return head->next;
}
};
(*^▽^*)