package main
import (
"fmt"
"math/rand"
)
type Student struct {
Name string
Age int
Score float32
next *Student
}
// 要想通过函数改变外面的变量的值 必须传进去这个变量的地址 而不是值
func insertHead(p **Student){
for i:=0; i<10; i++ {
stu := Student{
Name: fmt.Sprintf("stu%d", i),
Age: rand.Intn(100),
Score: rand.Float32() * 100,
}
stu.next = *p
*p = &stu
}
}
func trans(p *Student){
for p != nil {
fmt.Println(*p)
p = p.next
}
}
func main(){
var head *Student = new(Student)
head.Name = "zyn"
head.Age = 3
head.Score = 100.0
insertHead(&head)
trans(head)
}
golang简单实现链表头部插入方法封装,对指针 和 方法的理解需要一点基础
最新推荐文章于 2022-07-10 22:33:19 发布