Junedayday Blog

六月天天的个人博客

0%

Go算法实战 - 2.【两数相加LeetCode-2】非递归解法

Go-Leetcode

Leetcode-2 两数相加

原题链接 https://leetcode-cn.com/problems/add-two-numbers/

我们继续看上一个题目,这次我们尝试写一个非递归的解法。

1
2
3
4
5
6
7
type ListNode struct {
Val int
Next *ListNode
}

func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
}

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
// walker是为了在l1/l2里遍历,修改Next指针
var carry, sentinel, walker = 0, l1, l1

for {
if l1 != nil {
if walker != l1 {
walker.Val += l1.Val
}
l1 = l1.Next
}
if l2 != nil {
if walker != l2 {
walker.Val += l2.Val
}
l2 = l2.Next
}
walker.Val += carry
carry, walker.Val = walker.Val/10, walker.Val%10

// 这里很重要,指定的是walker.Next的指向,能解决l1/l2跨链表的访问
if l1 != nil {
walker.Next = l1
} else if l2 != nil {
walker.Next = l2
} else if carry > 0 {
walker.Next = new(ListNode)
} else {
break
}
walker = walker.Next
}

return sentinel
}

Github: https://github.com/Junedayday/code_reading

Blog: http://junes.tech/

Bilibili: https://space.bilibili.com/293775192

公众号: golangcoding

二维码