package main标签:node,LinkStack,linkStack,链表,link,go,root,size From: https://www.cnblogs.com/zxqblogrecord/p/17590675.html
import "fmt"
//链表栈
type LinkStack struct {
root *LinkNode //栈顶
size int //栈的元素数量
}
//栈中的结点
type LinkNode struct {
data int
next *LinkNode
}
func NewLinkStack() *LinkStack {
return &LinkStack{root: nil, size: 0}
}
//入栈
func (link *LinkStack) pushLinkStack(v int) {
//如果栈是空的
if link.root == nil {
node := new(LinkNode)
node.data = v
link.root = node
} else {
//栈不是空的,栈顶是链表头结点,栈底是链表尾结点,入栈的元素为新的头结点,并指向原来的结点
pre := link.root
node := new(LinkNode)
node.data = v
node.next = pre
link.root = node
}
link.size++
}
//出栈 栈顶的元素弹出
func (link *LinkStack) popLinkStack() int {
if link.size == 0 {
panic("empty")
}
top := link.root
v := top.data
link.root = top.next
link.size--
return v
}
//展示栈
func (link *LinkStack) showLinkStack() {
if link.root == nil {
return
}
head := link.root
fmt.Printf("-------------- \n")
for head != nil {
fmt.Printf("栈的元素展示 %v \n", head.data)
head = head.next
}
fmt.Printf("-------------- \n")
}
//栈的大小
func (link *LinkStack) lenLinkStack() int {
fmt.Printf("link 长度 %v", link.size)
return link.size
}
//栈是否为空
func (link *LinkStack) IsEmpty() bool {
return link.size == 0
}
func main() {
linkStack := NewLinkStack()
linkStack.pushLinkStack(12)
linkStack.pushLinkStack(13)
linkStack.showLinkStack()
linkStack.pushLinkStack(17)
linkStack.lenLinkStack()
linkStack.showLinkStack()
linkStack.popLinkStack()
linkStack.showLinkStack()
}