leetcode 链表 加减法
package main
import "fmt"
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
type ListNode struct {
Val int
Next *ListNode
}
func main() {
var firstNode ListNode
firstNode.Val = 2
firstNode.Next = nil
var twoNode ListNode
twoNode.Val = 4
firstNode.Next = &twoNode
var threeNode ListNode
threeNode.Val = 3
twoNode.Next = &threeNode
printAllList(&firstNode)
linkedList := NewLinkList()
linkedList.Val = 5
linkedList.Insert(1,6)
linkedList.Insert(2,4)
printAllList(linkedList)
linkedListSum := addTwoNumbers(&firstNode, linkedList)
printAllList(linkedListSum)
//var arraySumIndex []int
}
func printAllList(firstNode *ListNode){
printNode := firstNode
for printNode != nil {
fmt.Printf("printNode Val =%d \n", printNode.Val)
printNode = printNode.Next
}
}
//Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
//Output: 7 -> 0 -> 8
// 5+ 5 = 10
// 1 8 0 --> 18
//Explanation: 342 + 465 = 807.
func addTwoNumbers(l1 *ListNode, l2 *ListNode) *ListNode {
flag := 0; // 进位,给下一次用
var CurrNode *ListNode
CurrNode = nil
firstNode := CurrNode
curl1 := l1
curl2 := l2
for curl1 != nil || curl2 != nil {
answer := 0
answer += flag
if (curl1 != nil){
answer += curl1.Val
curl1 = curl1.Next
}
if (curl2 != nil){
answer += curl2.Val
curl2 = curl2.Next
}
CurAnswerNode := NewLinkList()
flag = answer/10
CurAnswerNode.Val = answer%10
CurAnswerNode.Next = nil
if (CurrNode == nil){
firstNode = CurAnswerNode
CurrNode = firstNode
} else{
CurrNode.Next = CurAnswerNode;
CurrNode = CurAnswerNode
}
}
if (flag != 0){
answer := flag
CurAnswerNode := NewLinkList()
//flag = answer/10
CurAnswerNode.Val = answer%10
CurAnswerNode.Next = nil
CurrNode.Next = CurAnswerNode;
}
//fmt.Println("answer")
//printAllList(firstNode)
return firstNode
}
//生成头节点
func NewLinkList() *ListNode {
//下面的data可以用来表示链表的长度
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
}