package main
import (
"sync"
"fmt"
)
func main() {
node := Instance()
node.Name = "张三"
node1 := &Node{Name: "李四"}
node2 := &Node{Name: "赵武"}
node3 := &Node{Name: "李刘"}
InsertNode(node, node1)
InsertNode(node, node2)
InsertNode(node, node3)
ListNode(node)
}
type Node struct {
Name string
NodePtr *Node
}
var node *Node
var once sync.Once
func Instance() (*Node) {
once.Do(func() {
if node == nil {
node = &Node{}
}
})
return node
}
//单链表追加节点
func InsertNode(oldNode, newNode *Node) {
for {
if oldNode.NodePtr == nil {
break
}
//地址指向下一个节点的地址
oldNode = oldNode.NodePtr
}
oldNode.NodePtr = newNode
}
func ListNode(node *Node) {
if node.NodePtr == nil {
return
}
for {
fmt.Printf("NodeName==>%s==>", node.Name)
node = node.NodePtr
if node.NodePtr == nil {
fmt.Printf("NodeName==>%s", node.Name)
break
}
}
}
输出结果
NodeName==>张三==>NodeName==>李四==>NodeName==>赵武==>NodeName==>李刘
Process finished with exit code 0
网友评论