栈的链式存储结构及实现


 对于链表来说,基本不存在栈满的情况,除非内存已经没有可使用的空间。

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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值