Go语言数据结构和算法-使用Slice实现栈
栈是Last-In-First-Out (LIFO)(后进先出)的数据结构,对应的接口如下:
New() //初始化栈Push() // 压栈Pop() // 出栈,返回栈顶的数据并删除栈顶的数据Top() // 返回栈顶的数据 不删除栈顶的数据Size() // 返回栈的大小
利用Go语言的Slice的特性实现栈的结构
type Stack struct { elements []interface{} lock sync.RWMutex }
New()
func (s *Stack) New() *Stack { s.elements = []interface{}{} return s }
Push()
func (s *Stack) Push(item interface{}) { s.lock.Lock() defer s.lock.Unlock() s.elements = append(s.elements, item) }
Pop()
func (s *Stack) Pop() interface{} { s.lock.Lock() defer s.lock.Unlock() index := len(s.elements) - 1 item := s.elements[index] s.elements = s.elements[0:index] return item }
Top()
func (s *Stack) Top() interface{} { s.lock.Lock() defer s.lock.Unlock() index := len(s.elements) - 1 return s.elements[index] }
Size()
func (s *Stack) Size() int { s.lock.Lock() defer s.lock.Unlock() return len(s.elements) }
作者:CoderMiner
链接:https://www.jianshu.com/p/b0f8c189738d
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦