对于链表来说,基本不存在栈满的情况,除非内存已经没有可使用的空间。
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()) //3
fmt.Println()
fmt.Printf("top value:%v\n",ls.Pop()) // 300
fmt.Printf("top value:%v\n",ls.Pop()) // 200
fmt.Printf("top value:%v\n",ls.Pop()) // 100
fmt.Printf("size:%v\n",ls.GetSize()) //0
fmt.Printf("top value:%v\n",ls.Pop()) // nil
ls.Push(10)
ls.Push(20)
ls.Push(30)
fmt.Printf("top:%v\n",ls.GetTop()) //30
//fmt.Printf("is empty:%v\n",ls.Empty())
//ls.Clear()
//fmt.Printf("is empty:%v\n",ls.Empty())
fmt.Printf("size:%v\n",ls.GetSize()) //3
fmt.Printf("list :%v\n",ls.Range()) //30,20,10
}
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]
栈的链式存储结构及实现
最新推荐文章于 2022-04-03 09:00:00 发布
280

被折叠的 条评论
为什么被折叠?



