加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

栈的实现

发布时间:2020-12-15 04:48:21 所属栏目:百科 来源:网络整理
导读://采用切片作为底层结构 package main import ( "reflect" "fmt" ) type Stack struct { Values []interface{} Type reflect.Type } func NewStack(valueType reflect.Type)*Stack { return Stack{Values:make([]interface{},0),Type:valueType} } //判断是

//采用切片作为底层结构

package main

import (

"reflect"

"fmt"

)

type Stack struct {

Values []interface{}

Type reflect.Type

}

func NewStack(valueType reflect.Type)*Stack {

return &Stack{Values:make([]interface{},0),Type:valueType}

}

//判断是否符合栈类型

func (s *Stack) CheckValue(data interface{}) bool{

if data == nil || reflect.TypeOf(data) != s.Type {

return false

}

return true

}

//判断栈是否为空

func (s *Stack) Empty()bool {

if len(s.Values) == 0{

return true

}

return false

}

//栈的大小

func (s *Stack) Size()int {

return len(s.Values)

}

//获取栈顶元素

func (s *Stack) Top() interface{}{

if s.Empty() {

return nil

}

return s.Values[len(s.Values)-1]

}

//获取栈的元素类型

func (s *Stack) ValueType() reflect.Type{

return s.Type

}

//push

func (s *Stack) Push(data interface{})bool {

if !s.CheckValue(data) {

return false

}

s.Values = append(s.Values,data)

return true

}

//pop

func (s *Stack) Pop()(interface{},bool){

if s.Empty() {

return nil,false

}

value := s.Values[s.Size()-1]

s.Values = s.Values[:s.Size()-1]

return value,true

}

func main() {

stack := NewStack(reflect.TypeOf(2))

stack.Push(1)

stack.Push("2")

stack.Push("3")

stack.Push("4")

fmt.Println(stack.Values)

}

//也可以使用container/list包,更为简洁

package main

import (

"fmt"

"container/list"

)

type Stack struct {

List *list.List

}

func NewStack()*Stack{

return &Stack{List:list.New()}

}

//push

func (s *Stack) Push(data interface{}){

s.List.PushBack(data)

}

//pop

func (s *Stack) Pop() interface{}{

l := s.List.Back()

return s.List.Remove(l)

}

func main() {

stack := NewStack()

stack.Push(1)

stack.Push(2)

stack.Push(3)

stack.Push(4)

stack.Push(5)

fmt.Println(stack.Pop())

fmt.Println(stack.Pop())

fmt.Println(stack.Pop())

//fmt.Println(stack.Pop())

for l := stack.List.Front();l != nil;l = l.Next() {

fmt.Println(l.Value)

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读