LeetCode Golang 单向链表相加 反向实现
LeetCode 两数之和, 反向实现
1 -> 2 -> 3 -> 4
+ 3 -> 4
----------------------------
1 -> 2 -> 6 -> 8
func addTwoNumbersReverse(l1 *ListNode, l2 *ListNode) *ListNode { if l1 == nil || l2 == nil { return nil } l := new(ListNode) l.Val = 0 tmp := l flag := 0 l1Arr := []int{} l2Arr := []int{} lRst := []int{} for l1 != nil { l1Arr = append(l1Arr, l1.Val) l1 = l1.Next } for l2 != nil { l2Arr = append(l2Arr, l2.Val) l2 = l2.Next } i := 0 for { if i > len(l1Arr)-1 || i > len(l2Arr)-1 { break } num := l1Arr[i]+l2Arr[i]+flag flag = 0 if num >= 10 { flag = 1 num = num % 10 } lRst = append(lRst,num) i++ } if i < len(l1Arr) { for ;i<len(l1Arr);i++{ if flag == 1 { lRst = append(lRst,l1Arr[i]+1) flag = 0 } else { lRst = append(lRst,l1Arr[i]) } } } if i < len(l2Arr) { for ;i<len(l2Arr);i++{ if flag == 1 { lRst = append(lRst,l2Arr[i]+1) flag = 0 } else { lRst = append(lRst,l2Arr[i]) } } } for i := len(lRst)-1; i >=0; i-- { tmp.Val = lRst[i] if i == 0 { break } tmp.Next = new(ListNode) tmp = tmp.Next } return l }
思路: 为了简化运算把所有链表中的值取出来到切片里进行相加, 然后再从切片写入到新的链表里
另一个思路: 借助昨天的代码, 再运算前对链表进行反转