题目
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.
两个链表相加,链表中均为非负整数。链表中的整数以倒序存放,即开头为个位,然后依次为十位、百位、千位等等……将相加之和以一个链表的结构返回。
- Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解题思路
思路很简单,同时循环两个链表,然后将相加的结果储存在新的链表中。但是题目有两个难点:
- 两个链表长度可能不相等:
- 解决方法是在短的链表尾部补0,然后与长链表相加
- 当相加的和大于10时,需要进位:
- 设置一个变量默认值为0,当和大于10时,变量的值为1,然后与下一位的和相加
/**
* 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) {
ListNode sum(0), *p = ∑
int carry = 0;
while(l1!=NULL || l2!=NULL || carry!=0) { // carry != 0 应对特殊情况如:【6】+【7】或者【64】+【36】,即,两个相同长度的链表相加产生进位的情况
if(l1) { // 循环 l1
carry += l1->val;
l1 = l1->next;
}
if(l2) { // 循环 l2
carry += l2->val;
l2 = l2->next;
}
p->next = new ListNode(carry%10);
carry = carry/10; // 保存进位
p = p->next;
}
return sum.next;
}
};
网友评论