doomli3721 2015-01-17 02:20
浏览 97
已采纳

如何在Golang中的列表中构造循环

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条回答 默认 最新

  • dousendun8411 2015-01-17 02:53
    关注

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

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改