对于链表来说,基本不存在栈满的情况,除非内存已经没有可使用的空间。
package main
import(
"fmt"
)
type StackNode struct{
Element interface{}
Next *StackNode
}
type LinkStack struct{
LinkStackTop *StackNode
Size int
}
func NewStack()*LinkStack{
return &LinkStack{}
}
func(this *LinkStack) Push(value interface{}){
if this.LinkStackTop == nil {
node := &StackNode{
Element:value,
}
this.LinkStackTop = node
}else{
node := &StackNode{
Element:value,
Next: this.LinkStackTop,
}
this.LinkStackTop = node
}
this.Size++
}
func (this *LinkStack) Pop() (value interface{}){
if this.LinkStackTop == nil {
return nil
}
value = this.LinkStackTop.Element
if this.LinkStackTop.Next != nil {
this.LinkStackTop = this.LinkStackTop.Next
}else{
this.LinkStackTop = nil
}
this.Size--
return
}
func (this *LinkStack) GetTop() (value interface{}){
if this.LinkStackTop == nil{
return nil
}
value = this.LinkStackTop.Element
return
}
func (this *LinkStack) GetSize() int{
return this.Size
}
func (this *LinkStack) Empty() bool{
if this.Size <=0 || this.LinkStackTop == nil {
return true
}
return false
}
func (this *LinkStack) Range()(list []interface{}){
node := this.LinkStackTop
if node == nil {
return
}
for{
list = append(list,node.Element)
if node.Next != nil {
node = node.Next
}else{
break
}
}
return
}
func (this *LinkStack) Clear(){
this.Size = 0
this.LinkStackTop = nil
}
func main(){
ls := NewStack()
ls.Push(100)
ls.Push(200)
ls.Push(300)
fmt.Printf("size:%v\n",ls.GetSize())
fmt.Println()
fmt.Printf("top value:%v\n",ls.Pop())
fmt.Printf("top value:%v\n",ls.Pop())
fmt.Printf("top value:%v\n",ls.Pop())
fmt.Printf("size:%v\n",ls.GetSize())
fmt.Printf("top value:%v\n",ls.Pop())
ls.Push(10)
ls.Push(20)
ls.Push(30)
fmt.Printf("top:%v\n",ls.GetTop())
fmt.Printf("size:%v\n",ls.GetSize())
fmt.Printf("list :%v\n",ls.Range())
}
go run linkStack.go
size:3
top value:300
top value:200
top value:100
size:0
top value:<nil>
top:30
size:3
list :[30 20 10]