Loops 我的迭代函数有什么问题
我试图迭代一个简单的链表。这应该很简单,但不起作用。迭代函数包含问题Loops 我的迭代函数有什么问题,loops,pointers,go,linked-list,Loops,Pointers,Go,Linked List,我试图迭代一个简单的链表。这应该很简单,但不起作用。迭代函数包含问题 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} cur
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)
}
}
对于kicks,我尝试了另一个版本的迭代循环,它使用一个函数来获取。我的想法是可能是头部。由于某种循环优化,下一个总是指向我原来的头部。这个理论似乎不正确
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,这等于下一个节点。下一个head不应该返回下一个节点,直到我们到达一个nil节点并退出循环
---更新---
我对iterate做了如下修改,现在它更干净、更正确了:
func iterate(head *Node) {
for ; head != nil; head = head.Next {
fmt.Printf("head %+v head.Next %+v\n", head, head.Next)
}
}
查看以下内容:
- 循环的“init语句”部分(
)只计算一次n:=head.Next
- post语句不断将
重置为head
的初始值(n
)getNext(head)
n:=getNext(head)
应该更好,如下所示:
n:=head.Next
只运行一次
在中①; ②; ③ { ④ }代码>
它运行① - ②④③ - ②④③ - ②④③ - ...
所以你应该把迭代放进去③, 当然,你可以把它放进去② 或④ 但这不是很明显。谢谢!当我阅读你链接的文档时,我的脸是掌心的。现在想想,这很有意义。你的修改肯定比我的更干净;)我只是尽量少修改你的循环初始版本。
func iterate(head *Node) {
for ; head != nil; head = head.Next {
fmt.Printf("head %+v head.Next %+v\n", head, head.Next)
}
}
for n := head; n != nil; head = n {
fmt.Printf("head %+v n %+v\n", head, n)
time.Sleep(time.Second * 1)
n = head.Next
}