英文:
How to construct a loop in a list in golang
问题
我写了一个使用Go语言在列表中查找循环的函数。但是我无法构造一个循环列表作为输入。
请看下面的代码:
package main
import (
"container/list"
"fmt"
)
func main() {
l := list.New()
l.PushBack(0)
l.PushBack(1)
l.PushBack(2)
l.PushBack(3)
l.PushBack(4)
l.PushBack(5)
e6 := l.PushBack(6)
l.PushBack(7)
e8 :=l.PushBack(8)
e9 := l.InsertAfter(9,e8)
l.InsertBefore(e9, e6)
for e:=l.Front() ; e !=nil ; e=e.Next() {
fmt.Println(e.Value)
}
}
有人可以帮我解决这个问题吗?
英文:
I wrote a function to find the loop in a list using golang. But I am not able to construct a loop in a list as input.
Please find below the code,
package main
import (
"container/list"
"fmt"
)
func main() {
l := list.New()
l.PushBack(0)
l.PushBack(1)
l.PushBack(2)
l.PushBack(3)
l.PushBack(4)
l.PushBack(5)
e6 := l.PushBack(6)
l.PushBack(7)
e8 :=l.PushBack(8)
e9 := l.InsertAfter(9,e8)
l.InsertBefore(e9, e6)
for e:=l.Front() ; e !=nil ; e=e.Next() {
fmt.Println(e.Value)
}
}
could anyone help me on this?
答案1
得分: 2
使用container/list包中的List类型无法构建循环。List类型的方法确保没有循环。因为list.Element的next和previous指针没有导出,应用程序无法通过直接修改元素来创建循环。
您可以定义自己的类型来创建一个带有循环的列表:
package main
import "fmt"
type node struct {
v int
next *node
}
func main() {
// 创建包含1、2、3的列表并打印。
l := &node{1, &node{2, &node{3, nil}}}
for n := l; n != nil; n = n.next {
fmt.Println(n.v)
}
// 创建带有循环的列表并打印最多100步。
n3 := &node{3, nil}
l = &node{1, &node{2, n3}}
n3.next = l
for i, n := 0, l; n != nil && i < 100; n, i = n.next, i+1 {
fmt.Println(n.v)
}
}
英文:
It is not possible to construct a loop using the container/list List type. The List type methods ensure that there's no loop. Because the list Element's next and previous pointers are not exported, the application cannot create a loop by modifying the elements directly.
You can define your own type to create a list with a loop:
package main
import "fmt"
type node struct {
v int
next *node
}
func main() {
// Create list with 1, 2, 3 and print.
l := &node{1, &node{2, &node{3, nil}}}
for n := l; n != nil; n = n.next {
fmt.Println(n.v)
}
// Create list with loop and print at most 100 steps down the list.
n3 := &node{3, nil}
l = &node{1, &node{2, n3}}
n3.next = l
for i, n := 0, l; n != nil && i < 100; n, i = n.next, i+1 {
fmt.Println(n.v)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论