栈的实现

//采用切片作为底层结构
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)
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值