-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2.两数相加.go
100 lines (90 loc) · 1.26 KB
/
2.两数相加.go
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package main
/*
* @lc app=leetcode.cn id=2 lang=golang
*
* [2] 两数相加
*/
type ListNode struct {
Val int
Next *ListNode
}
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
add := false
l1_len := 0
l2_len := 0
var base *ListNode
var normal *ListNode
t1 := l1
t2 := l2
for {
if l1.Next != nil {
l1 = l1.Next
l1_len += 1
} else {
break
}
}
for {
if l2.Next != nil {
l2 = l2.Next
l2_len += 1
} else {
break
}
}
if l1_len > l2_len {
base = t1
normal = t2
} else {
base = t2
normal = t1
}
bas1 := base
for {
val2 := 0
if base == nil {
break
}
if normal == nil {
if add == false {
break
}
} else {
val2 = normal.Val
}
if add == true {
base.Val += 1
add = false
}
val1 := base.Val
val3 := val1 + val2
if val3 > 9 {
add = true
val3 = val3 - 10
}
base.Val = val3
if base.Next == nil && add == true {
base.Next = &ListNode{
Val: 1,
Next: nil,
}
add = false
}
base = base.Next
if normal == nil || normal.Next == nil {
normal = nil
} else {
normal = normal.Next
}
}
return bas1
}
// @lc code=end