package main
// You are given two linked lists representing two non-negative numbers. 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.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
import (
"container/list"
"fmt"
)
func main() {
l1 := list.New()
l1.PushBack(4)
l1.PushBack(5)
l1.PushBack(2)
l2 := list.New()
l2.PushBack(7)
l2.PushBack(3)
l3 := list.New()
l3 = addTwoNumbers(l1, l2)
for e := l3.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
}
func addTwoNumbers(l1 list, l2 list) (l3 list) {
int carry = 0
l4 := list.New()
e1 := l1.Front()
e2 := l2.Front()
for ;; {
int sum = carry
if l1 != nil {
sum += l1.Value
l1 = l1.Next()
}
if l2 != nil {
sum += l2.Value
l2 = l2.Next()
}
l4.PushBack(sum % 10)
carry = sum / 10
if l1== nil && l2 == nil && carry == 0{
break
}
}
return l4
}
我收到了错误:
./addTwoNumbers.go:26: syntax error: unexpected name, expecting semicolon or newline or }
./addTwoNumbers.go:31: syntax error: unexpected name, expecting semicolon or newline or }
但我不知道如何解决它。需要帮忙。感谢
答案 0 :(得分:2)
您的代码中存在大量错误。
after
变量的名称。大多数时候你不需要声明它Value
这是一个工作版本
http://play.golang.org/p/yys-OcxZz2
package main
// You are given two linked lists representing two non-negative numbers. 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.
// Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
// Output: 7 -> 0 -> 8
import (
"container/list"
"fmt"
)
func main() {
l1 := list.New()
l1.PushBack(4)
l1.PushBack(5)
l1.PushBack(2)
l2 := list.New()
l2.PushBack(7)
l2.PushBack(3)
l3 := list.New()
l3 = addTwoNumbers(l1, l2)
for e := l3.Front(); e != nil; e = e.Next() {
fmt.Println(e.Value)
}
}
func addTwoNumbers(l1 *list.List, l2 *list.List) (l3 *list.List) {
carry := 0
l4 := list.New()
e1 := l1.Front()
e2 := l2.Front()
for {
sum := carry
if e1 != nil {
sum += e1.Value.(int)
e1 = e1.Next()
}
if e2 != nil {
sum += e2.Value.(int)
e2 = e2.Next()
}
l4.PushBack(sum % 10)
carry = sum / 10
if e1 == nil && e2 == nil && carry == 0 {
break
}
}
return l4
}