一、栈数据结构特点
栈是一种“操作受限”的线性表,只允许在一端插入和删除数据。
当某个数据集合只涉及在一端插入和删除数据,并且满足后进先出、先进后出的特性,我们就应该首选“栈”这种数据结构。
栈主要包含两个操作,入栈和出栈,也就是在栈顶插入一个数据和从栈顶删除一个数据。
二、Go语言实现栈
栈既可以用数组来实现,也可以用链表来实现。用数组实现的栈,我们叫作顺序栈,用链表实现的栈,我们叫作链式栈。
链式栈Go语言实现
package StackBaseOnList
import "fmt"
type Node struct {
data interface{}
next *Node
}
type Stack struct {
topeNode *Node
}
func NewStack()*Stack{
return &Stack{
nil,
}
}
func (this *Stack)Push(value interface{}){
this.topeNode = &Node{data:value,next:this.topeNode}
}
func (this *Stack)isEmpty()bool{
if this.topeNode == nil {
return true
}
return false
}
func (this *Stack)Pop()interface{}{
if this.isEmpty(){
return nil
}
value := this.topeNode.data
this.topeNode = this.topeNode.next
return value
}
func (this *Stack) Top() interface{}{
if this.isEmpty(){
return nil
}
return this.topeNode.data
}
func (this *Stack) Print(){
if this.isEmpty(){
fmt.Println("empty Stack")
}
cur := this.topeNode
for nil != cur{
fmt.Println(cur.data)
cur = cur.next
}
}