鏈表是一個結點指向下一個結點的存盤結構,每一個結點有兩個元素,一個是存放資料本身,另一個資料指向下一個結點,由這些結點組成一個鏈表
思路:
- 需要先定義一個結點類包含兩個元素,一個資料,一個指向下一結點
- 定義一個鏈表,包含一個頭結點的元素
- 根據鏈表中頭結點中包含下一個結點回圈找到最后的結點,在最后增加新的結點
代碼實作
package main
import "fmt"
type Node struct {
data int
next *Node
}
type NodeList struct {
headNode *Node
}
func (this *NodeList) add(data int) {
node := Node{data: data, next: nil}
if this.headNode == nil {
this.headNode = &node
} else {
tmp := this.headNode
for tmp.next != nil {
tmp = tmp.next
}
tmp.next = &node
}
}
func (this *NodeList) showall() {
if this.headNode == nil {
fmt.Println("no data")
} else {
tmp := this.headNode
for tmp.next != nil {
fmt.Println(tmp.data)
tmp = tmp.next
}
fmt.Println(tmp.data)
}
}
func main() {
var nl = new(NodeList)
nl.add(1)
nl.add(2)
nl.add(3)
nl.add(4)
nl.showall()
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/172820.html
標籤:其他
上一篇:條件隨機場之淺出
