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