Go語言程式遍歷迴圈連結串列並列印其元素
在本文中,我們將瞭解如何建立一個 Go 語言程式來遍歷迴圈連結串列並使用簡單的 for 和 while 迴圈列印其元素。迴圈連結串列是一種資料結構,其中列表的最後一個元素連線到第一個元素,形成一個迴圈。
演算法
步驟 1 − 首先,我們需要匯入 fmt 包。此結構包含一個數據變數用於儲存資料以及一個指標變數用於儲存下一個節點的地址。
步驟 2 − 然後建立一個名為 Traverse() 的函式來遍歷列表的元素。此函式使用 for 迴圈列印相應的元素。
步驟 3 − 現在,建立 main() 函式。在 main() 內部,為名為 head 的結構體建立一個節點,併為其賦值。
步驟 4 − 以這種方式建立多個節點,方法是將下一個節點的地址放置到 head 節點的 next 指標中,並將不同的值分配給所有這些節點的資料變數。
步驟 5 − 要遍歷此列表,請透過將 head 節點作為引數傳遞給函式來呼叫 traverse() 函式,並在螢幕上以迴圈方式列印列表的元素。
示例 1
在本例中,我們將編寫一個 Go 語言程式來遍歷迴圈連結串列並使用 for 迴圈列印其元素。這是遍歷迴圈連結串列最簡單的方法。在這裡,我們將從列表的頭部開始,並迭代迴圈,直到再次到達頭部。
package main
import "fmt"
type Node struct {
data int
next *Node
}
func traverseCircularList(head *Node) {
current := head
elem := current.data
for {
fmt.Printf("%d ", current.data)
current = current.next
if current == head {
break
}
}
fmt.Println(elem)
}
func main() {
head := &Node{data: 10}
head.next = &Node{data: 20}
head.next.next = &Node{data: 30}
head.next.next.next = head
fmt.Println("The elements obtained by traversing over the circular linked list are:")
traverseCircularList(head)
}
輸出
The elements obtained by traversing over the circular linked list are: 10 20 30 10
示例 2
在本例中,我們將編寫一個 Go 語言程式來透過 while 迴圈遍歷迴圈連結串列。
package main
import "fmt"
type Node struct {
data int
next *Node
}
func traverseCircularList(head *Node) {
if head == nil {
return
}
fmt.Println("The elements of the circular linked list are:")
current := head
for current.next != head {
fmt.Printf("%d ", current.data)
current = current.next
}
fmt.Printf("%d ", current.data)
}
func main() {
head := &Node{data: 11}
head.next = &Node{data: 12}
head.next.next = &Node{data: 13}
head.next.next.next = head
traverseCircularList(head)
}
輸出
The elements of the circular linked list are: 11 12 13
結論
我們已經成功編譯並執行了一個 Go 語言程式,用於遍歷迴圈連結串列並在螢幕上列印其元素,以及示例。我們在本文中使用了兩個程式。在第一個程式中,我們使用 for 迴圈,而在第二個程式中,我們使用 while 迴圈來實現結果。所有三種方法都非常有效且易於實現,方法的選擇取決於個人喜好和編碼風格。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP