C# · 12月 20, 2021

栈的实现

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

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)

}

}