0

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.