1. 程式人生 > >兩數相加 (golang)

兩數相加 (golang)

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
}
參考

單鏈表