在 Go 語言中實現迴圈連結串列
在本文中,我們將學習如何編寫一個 Go 語言程式,使用結構和切片方法實現迴圈連結串列。迴圈連結串列的建立方式是連結串列中的每個節點都指向下一個節點,而最後一個節點又指向起始節點。
例項 1
在此例項中,我們將編寫一個 Go 語言程式,使用結構來儲存列表中的每個節點,進而實現迴圈連結串列。
package main
import "fmt"
type Node struct {
data int
next *Node
}
type CircularLinkedList struct {
head *Node
tail *Node
}
func NewCircularLinkedList() *CircularLinkedList {
return &CircularLinkedList{head: nil, tail: nil}
}
func (cll *CircularLinkedList) IsEmpty() bool {
return cll.head == nil
}
func (cll *CircularLinkedList) AddNode(data int) {
newNode := &Node{data: data, next: nil}
if cll.IsEmpty() {
cll.head = newNode
cll.tail = newNode
newNode.next = cll.head
} else {
cll.tail.next = newNode
cll.tail = newNode
newNode.next = cll.head
}
}
func (cll *CircularLinkedList) Traverse() {
if cll.IsEmpty() {
fmt.Println("Circular Linked List is empty")
} else {
current := cll.head
for {
fmt.Printf("%d -> ", current.data)
current = current.next
if current == cll.head {
break
}
}
fmt.Printf("%d\n", cll.head.data)
}
}
func main() {
cll := NewCircularLinkedList()
fmt.Println("The nodes of circular linked list are:")
cll.AddNode(1)
cll.AddNode(2)
cll.AddNode(3)
cll.AddNode(4)
cll.AddNode(5)
cll.Traverse()
}
輸出
The nodes of circular linked list are: 1 -> 2 -> 3 -> 4 -> 5 -> 1
例項 2
在此例項中,我們將編寫一個 Go 語言程式,使用切片來儲存列表中的值,進而實現迴圈連結串列。
package main
import (
"fmt"
)
type CircularLinkedList struct {
values []int
size int
}
func (cll *CircularLinkedList) AddNode(value int) {
cll.values = append(cll.values, value)
cll.size++
}
func (cll *CircularLinkedList) RemoveNode(value int) bool {
for i, v := range cll.values {
if v == value {
cll.values = append(cll.values[:i], cll.values[i+1:]...)
cll.size--
return true
}
}
return false
}
func (cll *CircularLinkedList) PrintList() {
for i := 0; i < cll.size; i++ {
fmt.Printf("%d -> ", cll.values[i%cll.size])
}
fmt.Printf("%d", cll.values[0])
fmt.Println()
}
func main() {
cll := &CircularLinkedList{[]int{}, 0}
// add nodes
cll.AddNode(1)
cll.AddNode(2)
cll.AddNode(3)
cll.AddNode(4)
fmt.Println("The obtained circular linked list is:")
cll.PrintList()
cll.RemoveNode(3)
fmt.Println()
fmt.Println("The circular linked list obtained after removing node 3 are:")
cll.PrintList()
}
輸出
The obtained circular linked list is: 1 -> 2 -> 3 -> 4 -> 1 The circular linked list obtained after removing node 3 are: 1 -> 2 -> 4 -> 1
結論
我們已經成功地編譯並執行了一個 Go 語言程式,用例項展示瞭如何實現迴圈連結串列。我們在這裡使用了兩個程式。在第一個程式中,我們使用結構來儲存列表中節點的值和位置,而在第二個程式中,我們使用切片來儲存資料。
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP