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
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 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...
- Description You are given two non-empty linked lists repr...
- 一個(gè)循環(huán)內(nèi)從左向右加,當(dāng)l1==NULL && l2==NULL 退出,如果有進(jìn)位額外申請(qǐng)一個(gè)節(jié)點(diǎn)保存進(jìn)位: