package main
import "container/list"
type List[T any] list.List
func (c *List[T]) getList() *list.List { return (*list.List)(c) }
func (c *List[T]) PushBack(v T) { c.getList().PushBack(v) }
func (c *List[T]) Range(f func(i int, v T) bool) {
for i, j := c.getList().Front(), 0; i != nil; i = i.Next() {
if !f(j, i.Value.(T)) {
return
}
j++
}
}
func main() {
q := new(List[int])
q.PushBack(1)
q.PushBack(1)
q.PushBack(2)
q.PushBack(3)
q.PushBack(5)
for i, v := range q.Range {
println(i, v)
}
}
1
MoYi123 101 天前
type Node struct {
Left *Node Right *Node Val int } type TreeVisiter struct { root *Node } func makeNode(val int) *Node { return &Node{Val: val} } func (fr *TreeVisiter) InOrder(visit func(*Node) bool) { fr.p_inOrder(visit, fr.root) } func (fr *TreeVisiter) p_inOrder(visit func(*Node) bool, cur *Node) { if cur.Left != nil { if !visit(cur.Left) { return } } if !visit(cur) { return } if cur.Right != nil { if !visit(cur.Right) { return } } } func main() { root := makeNode(2) root.Left = makeNode(1) root.Right = makeNode(3) tv := TreeVisiter{root: root} for node := range tv.InOrder { if node.Val == 1 { fmt.Printf("first node is %d\n", node.Val) } if node.Val == 2 { fmt.Printf("second node is %d\n", node.Val) break } } } 中序遍历二叉树, 这个至少比 cpp 的 begin,end 好多了, 我公司项目里写的 cpp 的用来遍历树的 forward_iterator 写了快 300 行, 虽然情况也比这个复杂很多. |