連結串列是一個結點指向下一個結點的儲存結構,每一個結點有兩個元素,一個是存放資料本身,另一個資料指向下一個結點,由這些結點組成一個連結串列
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()
}