package main
import (
"fmt"
)
//定义结构体 注意点:go不支持类型别名,type与C语言中的typedef并不一样
/*
var a int
a = 3
type INT int
var b INT
b = 3
fmt.Println(a == b)
报错:invalid operation: a == b (mismatched types int and INT)
*/
type Node struct {
Value int
Next *Node
}
//测试链表是否为空
func IsEmpty(list *Node) bool {
return list == nil
}
//测试是否为最后节点
func IsLast(position *Node, list *Node) bool {
return position.Next == nil
}
func Find(value int, list *Node) *Node {
p := list
for p.Value != value {
p = p.Next
}
return p
}
//插入节点
func Insert(value int, list *Node, position *Node) {
tempCell := new(Node)
if tempCell == nil {
fmt.Println("out of space!")
}
tempCell.Value = value
tempCell.Next = position.Next
position.Next = tempCell
}
//删除节点
func Delete(value int, list *Node) {
pPrev := FindPrevious(value, list)
p := Find(value, list)
pPrev.Next = p.Next
p = nil
}
func FindPrevious(value int, list *Node) *Node{
p := list
for p.Next != nil && p.Next.Value != value {
p = p.Next
}
return p
}
//删除链表 注意点:Golang中函数传递指针变量,其实是传递实参
func DeleteList(list **Node) {
p := list
for *p != nil {
tmp := *p
*p = nil
*p = tmp.Next
}
}
//打印列表
func PrintList(list *Node) {
p := list
for p != nil {
fmt.Printf("%d-%p-%p ", p.Value, p, p.Next)
p = p.Next
}
fmt.Println()
}
func main() {
headNode := &Node{
Value:0,
Next:nil,
}
list := headNode
Insert(1, list, headNode)
PrintList(list)
fmt.Println(IsEmpty(list))
fmt.Println(IsLast(headNode, list))
p := Find(0, list)
Insert(2, list, p)
PrintList(list)
Delete(1, list)
PrintList(list)
DeleteList(&list)
PrintList(list)
}
Golang实现单链表
最新推荐文章于 2024-07-19 12:52:15 发布