码迷,mamicode.com
首页 > 编程语言 > 详细

Go语言栈定义及相关方法实现

时间:2017-04-12 16:08:39      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:false   interface   ble   err   pen   ast   erro   入栈   pack   

// stack 栈
package Algorithm

import (
    "errors"
    "reflect"
)

// 栈定义
type Stack struct {
    values    []interface{}
    valueType reflect.Type
}

// 构造栈
func NewStack(valueType reflect.Type) *Stack {
    return &Stack{values: make([]interface{}, 0), valueType: valueType}
}

// 判断值是否符合栈类型
func (stack *Stack) isAcceptableValue(value interface{}) bool {
    if value == nil || reflect.TypeOf(value) != stack.valueType {
        return false
    }
    return true
}

// 入栈
func (stack *Stack) Push(v interface{}) bool {
    if !stack.isAcceptableValue(v) {
        return false
    }
    stack.values = append(stack.values, v)
    return true
}

// 出栈
func (stack *Stack) Pop() (interface{}, error) {
    if stack == nil || len(stack.values) == 0 {
        return nil, errors.New("stack empty")
    }
    v := stack.values[len(stack.values)-1]
    stack.values = stack.values[:len(stack.values)-1]
    return v, nil
}

// 获取栈顶元素
func (stack *Stack) Top() (interface{}, error) {
    if stack == nil || len(stack.values) == 0 {
        return nil, errors.New("stack empty")
    }
    return stack.values[len(stack.values)-1], nil
}

// 获取栈内元素个数
func (stack *Stack) Len() int {
    return len(stack.values)
}

// 判断栈是否为空
func (stack *Stack) Empty() bool {
    if stack == nil || len(stack.values) == 0 {
        return true
    }
    return false
}

// 获取栈内元素类型
func (stack *Stack) ValueType() reflect.Type {
    return stack.valueType
}

 github链接地址:https://github.com/gaopeng527/go_Algorithm/blob/master/stack.go

Go语言栈定义及相关方法实现

标签:false   interface   ble   err   pen   ast   erro   入栈   pack   

原文地址:http://www.cnblogs.com/gaopeng527/p/6699666.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!