如何在Go语言中构建一个列表循环。

huangapple go评论99阅读模式
英文:

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)
    }

}

playground示例

英文:

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 &quot;fmt&quot;

type node struct {
    v    int
    next *node
}

func main() {
    // Create list with 1, 2, 3 and print.

    l := &amp;node{1, &amp;node{2, &amp;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 := &amp;node{3, nil}
    l = &amp;node{1, &amp;node{2, n3}}
    n3.next = l

    for i, n := 0, l; n != nil &amp;&amp; i &lt; 100; n, i = n.next, i+1 {
        fmt.Println(n.v)
    }

}

playground example

huangapple
  • 本文由 发表于 2015年1月17日 10:20:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/27995531.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定