gpt4 book ai didi

去收藏列表,如何将列表传递给函数?

转载 作者:数据小太阳 更新时间:2023-10-29 03:40:11 25 4
gpt4 key购买 nike

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 }

但是我不知道怎么解决。需要帮忙。谢谢

最佳答案

您的代码中有一堆错误。

  • 导入列表时,列表是模块名称而不是类型。使用 list.List
  • 在 go 中,类型是 变量名称之后。大多数时候你不需要申报
  • 遍历列表时使用元素而不是列表。元素有 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
}

关于去收藏列表,如何将列表传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27955787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com