標籤:false interface ble err pen ast erro 入棧 pack
// stack 棧package Algorithmimport ( "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語言棧定義及相關方法實現