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
type ListNode struct {
Val int
Next *ListNode
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
var head *ListNode=nil
var p *ListNode
var p1* ListNode =l1
var p2* ListNode=l2
var carry bool=false
for p1!=nil&&p2!=nil{
var tmp *ListNode=new(ListNode)
if carry{
tmp.Val=(p1.Val+p2.Val+1)%10
if(p1.Val+p2.Val+1)/10>0{
carry=true
}else {
carry=false
}
}else{
tmp.Val=(p1.Val+p2.Val)%10
if(p1.Val+p2.Val)/10>0{
carry=true
}else {
carry=false
}
}
tmp.Next=nil;
if head==nil{
head=tmp
p=tmp
}else {
p.Next=tmp
p=tmp
}
p1=p1.Next
p2=p2.Next
}
for p1!=nil{
if carry{
if (p1.Val+1)/10>0{
carry=true
}else {
carry=false
}
p1.Val=(p1.Val+1)%10
p.Next=p1
p=p1
p1=p1.Next
} else {
p.Next=p1
p=p1
p1=p1.Next
}
}
for p2!=nil{
if carry{
if (p2.Val+1)/10>0{
carry=true
}else {
carry=false
}
p2.Val=(p2.Val+1)%10
p.Next=p2
p=p2
p2=p2.Next
}else {
p.Next=p2
p=p2
p2=p2.Next
}
}
if carry{
var tmp *ListNode=new(ListNode)
tmp.Val=1
tmp.Next=nil
p.Next=tmp
p=tmp
}
return head
}