go:环形链表

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)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值