我知道要遍歷一個列表,我會執(zhí)行以下操作:for e := alist.Front(); e != nil; e = e.Next() { fmt.Println(e.Value) }但是,我想打印出每三個元素。在其他語言中,我會像 e += 3 這樣增加索引。如何使用 Go 來做到這一點?
1 回答

喵喔喔
TA貢獻1735條經驗 獲得超5個贊
List 是一個雙向鏈表,不允許按特定計數查找或跳轉。我的解決方法是這樣的:
i := 0
for e := alist.Front(); e != nil; e = e.Next() {
if i % 3 == 0 {
fmt.Println(e.Value)
}
i++
}
或者一個代碼重用的新函數(加上@torek的注釋,它變得更簡單了):
func NextByCount(el *list.Element, count int) *list.Element {
for ; el != nil && count > 0; count-- {
el = el.Next()
}
return el
}
然后像這樣循環(huán):
for e := alist.Front(); e != nil; e = NextByCount(e, 3) {
fmt.Println(e.Value)
}
- 1 回答
- 0 關注
- 194 瀏覽
添加回答
舉報
0/150
提交
取消