-
Notifications
You must be signed in to change notification settings - Fork 0
/
add-two-numbers-ii.go
71 lines (65 loc) · 1.23 KB
/
add-two-numbers-ii.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
package main
type ListNode struct {
Val int
Next *ListNode
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
l1 = reverseList(l1)
l2 = reverseList(l2)
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
var head, tail *ListNode
jinwei := 0
for left, right := l1, l2; left != nil || right != nil; {
val := 0
if left != nil {
val += left.Val
left = left.Next
}
if right != nil {
val += right.Val
right = right.Next
}
val += jinwei
node := &ListNode{val % 10, nil}
if head == nil {
head, tail = node, node
} else {
tail.Next = node
tail = tail.Next
}
jinwei = val / 10
if (left == nil || right == nil) && jinwei > 0 {
tail.Next = &ListNode{jinwei, nil}
}
}
return reverseList(head)
}
func reverseList(head *ListNode) *ListNode {
tail := head
for ; tail != nil && tail.Next != nil; tail = tail.Next {
}
head, _ = doReverse(head, tail)
return head
}
func doReverse(head, tail *ListNode) (*ListNode, *ListNode) {
if head == nil || tail == nil || head == tail {
return tail, head
}
pre, cur, next := head, head.Next, head.Next.Next
for {
cur.Next = pre
if cur == tail {
break
}
pre = cur
cur = next
next = next.Next
}
head.Next = nil
return tail, head
}