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 -> 8
C++
/**
* 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=l1;
int flag=0;
for(;;)
{
int val=(l1->val+l2->val+flag)%10;
flag=(l1->val+l2->val+flag)/10;
l1->val=val;
//结束循环条件是其中一个链表到达末尾了
if(l1->next == NULL || l2->next == NULL)
{
break;
}
l1=l1->next;
l2=l2->next;
}
//如果l2.Next不为空,就拼接到l1后面,否则不用做什么
if(l2->next!=NULL)
{
l1->next=l2->next;
}
//处理进位问题导致的合并之后链表的变更
for(;;)
{
//结束循环条件就是没有进位了,或到达了链表末尾
if(flag==0 || l1->next==NULL)
{
break;
}
l1=l1->next;
int val=(l1->val+flag)%10;
flag=(l1->val+flag)/10;
l1->val=val;
}
//处理最后一个进位
if(flag>0)
{
l1->next=new ListNode(flag);
}
return sum;
}
};
go:
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
sum:=l1
flag:=0
for{
Val:=(l1.Val+l2.Val+flag)%10
flag=(l1.Val+l2.Val+flag)/10
l1.Val=Val
if l1.Next== nil || l2.Next ==nil{
break
}
l1=l1.Next
l2=l2.Next
}
if l2.Next !=nil {
l1.Next=l2.Next
}
for flag >0 && l1 !=nil && l1.Next != nil{
l1=l1.Next
Val:=(l1.Val+flag)%10
flag=(l1.Val+flag)/10
l1.Val=Val
}
if flag>0{
l1.Next=&ListNode{}
l1=l1.Next
l1.Val=flag
l1.Next=nil
}
return sum
}