我试图遍历一个简单的链表。这应该很简单,但是没有用。迭代函数包含问题。
package main
import (
"fmt"
"time"
)
type Node struct {
Next *Node
Value int
}
func main() {
//Load up 100 *Node in a linked list (albeit a simple one)
head := &Node{Value: 0}
current := head
for i := 1; i < 100; i++ {
current.Next = &Node{Value: i}
current = current.Next
fmt.Printf("current %p %+v\n", current, current)
}
iterate(head)
}
//Iterate through the list starting at head. It never
//advances past the first "Next", loops forever.
func iterate(head *Node) {
for n := head.Next; n != nil; head = n {
fmt.Printf("head %+v n %+v\n", head, n)
time.Sleep(time.Second * 1)
}
}
iterate的输出如下所示:
head &{Next:0x20818c230 Value:0} n &{Next:0x20818c280 Value:1}
head &{Next:0x20818c280 Value:1} n &{Next:0x20818c280 Value:1}
head &{Next:0x20818c280 Value:1} n &{Next:0x20818c280 Value:1}
head &{Next:0x20818c280 Value:1} n &{Next:0x20818c280 Value:1}
head &{Next:0x20818c280 Value:1} n &{Next:0x20818c280 Value:1}
对于踢球,我尝试了另一个迭代循环的版本,该版本使用函数来获取.Next。我的想法是可能是头,由于某种循环优化,下一个总是指向我原来的头。该理论似乎是不正确的。
func iterate(head *Node) {
getNext := func (n *Node) *Node {
return n.Next
}
for n := getNext(head); n != nil; head = n {
fmt.Printf("head %+v n %+v\n", head, n)
time.Sleep(time.Second * 1)
}
}
天哪,我只是没看见吗?在循环体执行后,将head设置为n,它等于下一个Node。下一个头不应该。下一个返回下一个Node,直到我们到达nil节点并退出循环?
-更新-
我想出了以下修改来进行迭代,它更干净而且现在实际上可以纠正:
func iterate(head *Node) {
for ; head != nil; head = head.Next {
fmt.Printf("head %+v head.Next %+v\n", head, head.Next)
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句