環形單向鏈表
尚硅谷Golang課

環形單向鏈表

type CatNode struct {
	no   int
	name string
	next *CatNode
}

func Insert(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
	fmt.Println(*newCatNode, "已加入環形鏈表")
	newCatNode.next = head

}

func Del(head *CatNode, id int) *CatNode {
	temp := head
	helper := head
	if temp.next == nil {
		fmt.Println("這是一個空鏈表")
		return head
	}
	if temp.next == head { //只有一點
		temp.next = nil
		fmt.Println(id, "已刪除")
		return head
	}

	//helper放到尾
	for {
		if helper.next == head {
			break
		}
		helper = helper.next
	}

	flag := true
	for {
		if temp.next == head { //說明比到最後一個了
			break
		}
		if temp.no == id {
			if temp == head { //說明刪除的是頭
				head = head.next
			}
			helper.next = temp.next
			fmt.Println(id, "已刪除")
			flag = false
			break
		}
		temp = temp.next     //移動比較用
		helper = helper.next //一旦找到要刪除的點
	}
	if flag {
		if temp.no == id {
			helper.next = temp.next
			fmt.Println(id, "已刪除")
		} else {
			fmt.Println(id, "找不到")
		}
	}
	return head
}

func List(head *CatNode) {
	temp := head
	if temp.next == nil {
		fmt.Println("空的環形鏈表")
		return
	}
	for {
		fmt.Printf("貓id=%d name=%s ~>", temp.no, temp.name)
		if temp.next == head {
			break
		}
		temp = temp.next
	}
	fmt.Println()
}

func main() {
	head := &CatNode{}
	cat1 := &CatNode{
		no:   1,
		name: "tom",
	}
	cat2 := &CatNode{
		no:   2,
		name: "bbb",
	}
	cat3 := &CatNode{
		no:   3,
		name: "ccc",
	}

	Insert(head, cat1)
	Insert(head, cat2)
	Insert(head, cat3)
	List(head)
	// Del(head, 2)
	// List(head)
	head = Del(head, 4)
	List(head)

}

上次修改於 2021-09-01

此篇文章的評論功能已經停用。