题目
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 -> 8342+465 = 807
题意
有两个非空的链表代表两个正整数,正整数按照逆序存储,并且每个节点只含有一个数值,返回两个数之和用一个链表表示。
注意
- 这两个整数位数不确定,也就意味着两个链表的长度也是不相等的。
- 数值的存储是逆序的,返回的结果也是逆序的
- 两数之和,按位相加,产生进位,进位如何巧妙的到下一位?
思路
1.重新开辟一个链表用以存储累加之后的结果,虚拟头结点
2.进位的信息都存储在sum/=10中,在新的一轮循环累加在高位上
3.最高位产生进位,需要添加一个新节点值为1
代码
//时间复杂度O(n)
//空间复杂度O(n)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* cur1 = l1;
ListNode* cur2 = l2;
//虚拟链表头结点,用以存储加法之后的结果
ListNode* SumLink = new ListNode(0);
ListNode* new_sum = SumLink;
int sum = 0;
//当两个链表长度不相等时
while (cur1 != NULL||cur2 != NULL)
{
//进位改如何解决,当前的进位进入到下一轮可以叠加
sum /= 10;
if(cur1 != NULL)
{
//只有不为空才能next
sum += cur1->val;
cur1 = cur1->next;
}
if(cur2 != NULL)
{
sum += cur2->val;
cur2 = cur2->next;
}
ListNode* temp = new ListNode(sum%10);
new_sum->next = temp;
new_sum = new_sum->next;
}
//运行循环完毕,当最大位有进位的时候,直接插入1
if (sum /10 == 1)
{
new_sum->next = new ListNode(1);
}
return SumLink->next;
}
};