Golang程序:遍历循环链表并打印其元素
本文将介绍如何使用简单的for和while循环创建Golang程序,以遍历循环链表并打印其元素。循环链表是一种数据结构,其中列表的最后一个元素连接到第一个元素,形成一个循环。
算法
- 步骤1 - 首先,我们需要导入fmt包。这个结构体包含一个数据变量来存储数据以及一个指针变量来存储下一个节点的地址。
-
步骤2 - 然后创建一个名为Traverse()的函数,以遍历列表的元素。这个函数使用for循环打印各自的元素。
-
步骤3 - 现在,创建main()函数。在main()内部,创建一个名为head的结构体节点并给它赋值。
-
步骤4 - 以这种方式创建多个节点,通过把头节点的下一个指针的地址放置到下一个节点的位置,并为所有这些节点赋予不同的数据变量的值。
-
步骤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循环来实现结果。所有三种方法都是有效的且易于实现,方法的选择取决于个人偏好和编码风格。