循環鏈表還是挺有難度的:
- 向鏈表中插入第一條數據的時候如何進行初始化。
- 刪除循環鏈表中的數據時要考慮多種情況。
詳情在代碼中一一說明。
目錄結構如下:
circleLink.go
package link import ( "fmt" ) type CatNode struct { ID int Name string next *CatNode } func InserCatNode(head *CatNode, newCatNode *CatNode) { //初始化鏈表 //頭結點一開始是空的,當插入第一條數據時,進行初始化 if head.next == nil { head.ID = newCatNode.ID head.Name = newCatNode.Name head.next = head return } //定義一個臨時變量,找到環形的末尾,方便以后進行插入 tmp := head for { if tmp.next == head { tmp.next = newCatNode newCatNode.next = head break } else { tmp = tmp.next } } } func DeleteCatNode(head *CatNode, id int) *CatNode { //建立一個節點指向頭結點 tmp := head //如果頭結點.next為空,說明是空鏈表 if tmp.next == nil { fmt.Println("空鏈表") return head } //如果頭結點.next就是它自己,說明只有一個元素 if tmp.next == head { //判斷該元素是否是要刪除的,如果是,則將頭結點置為空 if tmp.ID == id { head.next = nil return head } else { fmt.Println("要刪除的id不存在") } } //獎勵一個輔助指針指向頭結點 helper := head //如果頭結點正好是我們要刪除的 if tmp.ID == id { fmt.Println("進入1") //如果頭結點.next不是指向它自己,說明除了頭結點之外還存在其它節點 if tmp.next != head { fmt.Println("進入2") //此時若想刪除頭結點,我們必須獲得一個新的頭結點 tmp = head.next //將helper遍歷到頭結點的前一位 for { if helper.next != head { helper = helper.next } else { //同時刪除掉原來的頭結點 fmt.Println("進入3") helper.next = head.next return tmp } } } else { //說明只有一個頭結點,且是我們要刪除的,直接將其置為空 tmp.next = nil } //如果頭結點不是我們要刪除的 } else { for { //如果找到一個節點是我們要刪除的 if tmp.next.ID == id { //刪除該節點 tmp2 := tmp.next tmp.next = tmp2.next break //如果找不到則繼續遍歷下一個節點 } else { tmp = tmp.next //如果下一個節點是頭結點,則表明完成遍歷,找不到要刪除的節點,並退出 if tmp.next == head { fmt.Println("未找到該條記錄") break } } } } return head } func ListCatNode(head *CatNode) { tmp := head if tmp.next == nil { fmt.Println("空環形鏈表") return } for { fmt.Printf("貓的信息為:id=%d,name=%s\n", tmp.ID, tmp.Name) if tmp.next == head { break } else { tmp = tmp.next } } }
main.go
package main import ( "fmt" "go_code/data_structure/link" ) func main() { head := &link.CatNode{} cat1 := &link.CatNode{ ID: 1, Name: "tom", } cat2 := &link.CatNode{ ID: 2, Name: "jack", } cat3 := &link.CatNode{ ID: 3, Name: "bob", } cat4 := &link.CatNode{ ID: 4, Name: "mike", } link.InserCatNode(head, cat1) link.InserCatNode(head, cat2) link.InserCatNode(head, cat3) link.InserCatNode(head, cat4) link.ListCatNode(head) fmt.Println("------------------------------") fmt.Println("刪除id=1后的結果是:") h1 := link.DeleteCatNode(head, 1) link.ListCatNode(h1) fmt.Println("------------------------------") fmt.Println("刪除id=4后的結果是:") h2 := link.DeleteCatNode(h1, 4) link.ListCatNode(h2) fmt.Println("------------------------------") fmt.Println("刪除id=3后的結果是:") h3 := link.DeleteCatNode(h2, 3) link.ListCatNode(h3) fmt.Println("------------------------------") fmt.Println("刪除id=2后的結果是:") h4 := link.DeleteCatNode(h3, 2) link.ListCatNode(h4) }
運行結果: