zoukankan      html  css  js  c++  java
  • Go语言栈定义及相关方法实现

    // 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

  • 相关阅读:
    Server 对象
    Response 对象
    bzoj 5252: [2018多省省队联测]林克卡特树
    bzoj 2167: 公交车站
    bzoj 5315: [Jsoi2018]防御网络
    bzoj 5319: [Jsoi2018]军训列队
    bzoj 4161: Shlw loves matrixI
    bzoj 4942: [Noi2017]整数
    bzoj 2648: SJY摆棋子
    kd-tree 小结
  • 原文地址:https://www.cnblogs.com/gaopeng527/p/6699666.html
Copyright © 2011-2022 走看看