链式栈
作者:互联网
链式栈
先进后出,FILO(first in last out)
入栈出栈都属于增删操作
操作方法
创建链式栈
打印链式栈
压栈
出栈
go实现
创建
type StackNode struct {
Data interface{}
Next *StackNode
}
func CreateStack(Data ...interface{}) *StackNode {
if Data == nil {
return nil
}
if len(Data) == 0 {
return nil
}
//创建链式栈对象
var stack *StackNode
//循环借助Data创建结点,并且按栈形数据结构,组织数据
for _, v := range Data {
newNode := new(StackNode)
newNode.Data = v
newNode.Next = stack
stack = newNode
}
return stack
}
打印链式栈
func PrintStack(s *StackNode) {
if s == nil {
return
}
for s != nil {
fmt.Println(s.Data)
s = s.Next
}
}
压栈(单向链表的头插法)
func PushStack(stack *StackNode, Data interface{}) *StackNode {
//容错
if s == nil {
return nil
}
if Data == nil {
return s
}
//创建新结点
newNode := new(StackNode)
newNode.Data = v
//压栈
newNode.Next = stack
stack = newNode
return stack
}
出栈
func PopStack(stack *StackNode) (*StackNode, interface{}) {
//容错
if s == nil {
return nil
}
return stack.Next, stack.Data
}
标签:return,nil,StackNode,链式,newNode,Data,stack 来源: https://blog.csdn.net/weixin_42506905/article/details/96495588