Add Two Numbers
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
完整代码:
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
//生成头节点
func New() *ListNode {
//下面的Val可以用来表示链表的长度
return &ListNode{0, nil}
}
//在链表的第i个位置前插入一个元素e,复杂度为o(n)
func (head *ListNode) Insert(i int, e int) bool {
p := head
j := 1
for nil != p && j < i {
p = p.Next
j++
}
if nil == p || j > i {
fmt.Println("pls check i:", i)
return false
}
s := &ListNode{Val: e}
s.Next = p.Next
p.Next = s
return true
}
//遍历链表
func (head *ListNode) Traverse() {
point := head.Next
for nil != point {
fmt.Println(point.Val)
point = point.Next
}
fmt.Println("--------done----------")
}
func main(){
l1 := New()
l1.Insert(1, 3)
l1.Insert(1, 4)
l1.Insert(1, 2)
l1.Traverse()
l2 := New()
l2.Insert(1, 4)
l2.Insert(1, 6)
l2.Insert(1, 5)
l2.Traverse()
result := addTwoNumbers(l1, l2)
result.Traverse()
}
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
head := &ListNode{0, nil}
current := head
carry := 0
for l1 != nil || l2 != nil || carry > 0 {
sum := carry
if l1 != nil {
sum += l1.Val
l1 = l1.Next
}
if l2 != nil {
sum += l2.Val
l2 = l2.Next
}
carry = sum / 10
current.Next = new(ListNode)
current.Next.Val = sum % 10
current = current.Next
}
return head.Next
}
// next 进入l的下一位。
func next(l *ListNode) *ListNode {
if l != nil {
return l.Next
}
return nil
}
func add(n1, n2 *ListNode, i int) (v, n int) {
if n1 != nil {
v += n1.Val
}
if n2 != nil {
v += n2.Val
}
v += i
if v > 9 {
v -= 10
n = 1
}
return
}