Golang程序 定义单链表
实例
解决这个问题的方法
第1步 - 我们来定义一个节点的结构。
第2步 - 使关联列表中的前一个节点存储下一个节点的地址。
例子
package main
import "fmt"
type Node struct {
value int
next *Node
}
func NewNode(value int) *Node{
var n Node
n.value = value
n.next = nil
return &n
}
func TraverseLinkedList(head *Node){
fmt.Printf("Linked List: ")
temp := head
for temp != nil {
fmt.Printf("%d ", temp.value)
temp = temp.next
}
}
func main(){
head := NewNode(30)
head.next = NewNode(10)
head.next.next = NewNode(40)
head.next.next.next = NewNode(40)
TraverseLinkedList(head)
}
输出
Linked List: 30 10 40 40