1 回答

TA貢獻2039條經(jīng)驗 獲得超8個贊
不可能使用容器/列表列表類型構(gòu)造循環(huán)。List 類型方法確保沒有循環(huán)。因為列表Element的 next 和 previous 指針沒有導出,應用程序無法通過直接修改元素來創(chuàng)建循環(huán)。
您可以定義自己的類型來創(chuàng)建帶有循環(huán)的列表:
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)
}
}
- 1 回答
- 0 關(guān)注
- 290 瀏覽
添加回答
舉報