如何创建一个带有循环的链表?

问题描述

确定单向链表是否包含循环是一个常见问题,您将如何创建带循环的链表?我正在尝试在 golang 中解决它。

package main

import "fmt"

type node struct {
    data            int
    nextnodepointer *node
}

type linkedList struct {
    headnode *node
    length   int
}

func (l *linkedList) prepend(n *node) {
    temp := l.headnode
    if l.headnode == nil {
        fmt.Println("headnode is nil")
        fmt.Println(n)
        temp = n.nextnodepointer
    }
    l.headnode = n
    n.nextnodepointer = temp
    l.length++
}

func (l linkedList) printData() {
    toPrint := l.headnode
    for l.length != 0 {
        fmt.Printf("%v\t",toPrint)
        toPrint = toPrint.nextnodepointer
        l.length--
    }
    fmt.Println()
}

func main() {
    var n1,n2,n3,n4,n5,n6 *node
    myList := linkedList{}
    n6 = &node{data: 60,nextnodepointer: n3}
    n5 = &node{data: 50,nextnodepointer: n6}
    n4 = &node{data: 40,nextnodepointer: n5}
    n3 = &node{data: 30,nextnodepointer: n4}
    n2 = &node{data: 20,nextnodepointer: n3}
    n1 = &node{data: 10,nextnodepointer: n2}

    myList.prepend(n6)
    myList.prepend(n5)
    myList.prepend(n4)
    myList.prepend(n3)
    myList.prepend(n2)
    myList.prepend(n1)
    myList.printData()
}

所以我试图像这样解决它,节点 n6 的下一个节点是 n3 但因为它在那一点上没有定义 n3nil这导致 printData 函数像这样打印链表的内容 &{10 0xc000010240} &{20 0xc000010230} &{30 0xc000010220} &{40 0xc000010210} &{50 0xc000010200} &{60 <nil>}。节点 n6 的下一个节点指针为 nil,因为 n3nil。如何在 golang 中创建带有循环的链表?

解决方法

在创建所有必要的节点后简单地创建循环:

 n6 = &node{data: 60}
 n5 = &node{data: 50,nextnodepointer: n6}
 n4 = &node{data: 40,nextnodepointer: n5}
 n3 = &node{data: 30,nextnodepointer: n4}
 n6.nextnodepointer=n3
 ...