package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func main() {
var l1 *ListNode
var l2 *ListNode
l1 = &ListNode{
Val:5,
Next:&ListNode{
Val:8,
Next:&ListNode{
Val:3,
},
},
}
l2 = &ListNode{
Val:5,
Next:&ListNode{
Val:6,
Next:&ListNode{
Val:4,
},
},
}
res := addTwoNumbers(l1,l2)
fmt.Println(res)
}
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode{
var l1List []int
var l2List []int
for tmp1 := l1;tmp1 != nil ;tmp1 = tmp1.Next {
l1List = append(l1List,tmp1.Val)
}
for tmp2 := l2;tmp2 != nil ;tmp2 = tmp2.Next {
l2List = append(l2List,tmp2.Val)
}
rem := 0
var res *ListNode
var resTmp *ListNode
maxLen := 0
if len(l1List) > len(l2List){
maxLen = len(l1List)+1
}else {
maxLen = len(l2List)+1
}
for i := 0;i<maxLen;i++{
l1Value := 0
if i>=len(l1List){
l1Value = 0
}else{
l1Value = l1List[i]
}
l2Value := 0
if i>=len(l2List){
l2Value = 0
}else{
l2Value = l2List[i]
}
count := l1Value + l2Value + rem
sum := 0
if count>=10{
rem = 1
sum = count-10
}else{
rem = 0
sum = count
}
if sum !=0 || i != maxLen-1{
if res == nil{
res = &ListNode{
Val:sum,
}
resTmp = res
}else{
resTmp.Next = &ListNode{
Val:sum,
}
resTmp = resTmp.Next
}
}
}
return res
}
add two nums
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Intersection of Two Arrays IIGiven two arrays, write a fu...
- Add Two Numbers (LeetCode) https://leetcode.com/problems/...
- ## 题目 >Add Two Numbers You are given two linked lists rep...