Golang 遍历循环链表并打印其元素
在本文中,我们将了解如何创建一个Golang程序来遍历循环链表并使用简单的for和while循环打印其元素。循环链表是一种数据结构,其中列表的最后一个元素连接到第一个元素,形成一个循环。
步骤
- 步骤1 - 首先,我们需要导入fmt包。这个结构体包含一个data变量来存储数据,以及一个指针变量来存储下一个节点的地址。
-
步骤2 - 然后创建一个名为Traverse()的函数来遍历列表的元素。该函数使用for循环来打印相应的元素。
-
步骤3 - 现在,创建main()函数。在main()函数内部,创建一个名为head的结构体节点,并为其赋值。
-
步骤4 - 以此类推,通过将下一个节点的地址放置在头节点的下一个指针中,并为所有这些节点的数据变量分配不同的值,创建多个节点。
-
步骤5 - 调用遍历()函数来遍历此链表,将头节点作为参数传递给函数,并在屏幕上以循环方式打印链表的元素。
示例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循环来实现结果。这三种方法都是有效且易于实现的,选择哪种方法取决于个人喜好和编码风格。