抛块砖演示下 range over func 用法

40 天前
 Nazz
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)
	}
}

1156 次点击
所在节点    Go 编程语言
2 条回复
MoYi123
40 天前
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 行, 虽然情况也比这个复杂很多.
ywc86340
38 天前

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1066340

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX