package main
import "fmt"
type CatNode struct {
no int
name string
next *CatNode
}
func InsteCatNode(head *CatNode, newCatNode *CatNode) {
//判断是不是第一只猫
if head.next == nil {
head.no = newCatNode.no
head.name = newCatNode.name
head.next = head //形成环形
fmt.Println(newCatNode, "加入到环形链表中")
return
}
//定义一个临时变量,帮忙找到环形最后的节点
temp := head
for {
if temp.next == head {
break
}
temp = temp.next
}
//加入到链表中
temp.next = newCatNode
newCatNode.next = head
}
//输出环形链表
func ListCircle(head *CatNode) {
temp := head
if temp.next == nil {
fmt.Println("NO")
return
}
for {
fmt.Println(temp.no, temp.name, "-->")
if temp.next == head {
break
}
temp = temp.next
}
}
//删除一个结点
func DelCatNode(head *CatNode, id int) *CatNode {
temp := head
hepler := head
if temp.next == nil {
fmt.Println("这是一个空链表")
return head
}
//如果只有一个结点
if temp.next == head {
temp.next = nil
return head
}
for {
if hepler.next == head {
break
}
hepler = hepler.next
}
//两个或者两个以上
flag := true
for {
if temp.next == head {
break
}
if temp.no == id {
if temp == head {
head = head.next
}
hepler.next = temp.next
fmt.Printf("%d已删除", id)
flag = false
break
}
temp = temp.next
hepler = hepler.next
}
if flag {
if temp.no == id {
hepler.next = temp.next
fmt.Printf("%d已删除", id)
} else {
fmt.Println("没有此id", id)
}
}
return head
}
func main() {
head := &CatNode{}
cat1 := &CatNode{
no: 1,
name: "tom",
}
cat2 := &CatNode{
no: 2,
name: "tom2",
}
cat3 := &CatNode{
no: 3,
name: "tom3",
}
InsteCatNode(head, cat1)
InsteCatNode(head, cat2)
InsteCatNode(head, cat3)
ListCircle(head)
head = DelCatNode(head, 30)
fmt.Println()
ListCircle(head)
}
go:环形链表
最新推荐文章于 2024-06-12 14:12:34 发布