Go语言栈实现

一、栈数据结构特点

栈是一种“操作受限”的线性表,只允许在一端插入和删除数据。

当某个数据集合只涉及在一端插入和删除数据,并且满足后进先出、先进后出的特性,我们就应该首选“栈”这种数据结构。

栈主要包含两个操作,入栈和出栈,也就是在栈顶插入一个数据和从栈顶删除一个数据。

二、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
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值