1. 程式人生 > 其它 >golang 學習用陣列模擬棧 參考

golang 學習用陣列模擬棧 參考

技術標籤:go langgolanggo

陣列模擬棧操作 感覺有待節儉

package stackShed

type stack struct {
	maxNumber        int //棧的最大容量
	spliceStackFloat []float32
	spliceStackStr   []string
	stackType        byte //1為數字棧   其他位字串棧
	stackTop         int  //棧頂初始化為-1
}

//建立一個棧 stackType:1為數字棧   其他位字串棧
func CreateStack(stackType byte,
maxNu int) stack { stResult := stack{ maxNumber: maxNu, stackType: stackType, stackTop: -1, } if stResult.stackType == 1 { stResult.spliceStackFloat = make([]float32, maxNu) } else { stResult.spliceStackStr = make([]string, maxNu) } return stResult } //數字入棧 func (its *stack) pushFloat
(val float32) bool { bl := false if its.maxNumber == its.stackTop+1 { return bl } else if its.stackType == 1 { its.stackTop++ its.spliceStackFloat[its.stackTop] = val bl = true } return bl } //字串入棧 func (its *stack) pushStr(val string) bool { bl := false if its.maxNumber == its.stackTop+
1 { return bl } else if its.stackType != 1 { its.stackTop++ its.spliceStackStr[its.stackTop] = val bl = true } return bl } //資料入棧 func (its *stack) Push(val interface{}) bool { //根據站型別轉化資料 var valFloat float32 // 感覺用這種方式進行型別推斷不太好,能否用反射減少程式碼量 switch val.(type) { case string: valStr, ok := val.(string) if !ok { return false } return its.pushStr(valStr) case int: valFloat = float32(val.(int)) case int16: valFloat = float32(val.(int16)) case float32: valFloat = val.(float32) case float64: valFloat = float32(val.(float64)) case uint: valFloat = float32(val.(uint)) case uint8: valFloat = float32(val.(uint8)) case uint16: valFloat = float32(val.(uint16)) case uint32: valFloat = float32(val.(uint32)) default: return false } return its.pushFloat(valFloat) } //資料出棧 func (its *stack) Pop() (interface{}, bool) { var result interface{} var resBl bool = false if its.stackTop != -1 { if its.stackType == 1 { if its.spliceStackFloat == nil { return result, resBl } result = its.spliceStackFloat[its.stackTop] its.stackTop-- resBl = true } else { if its.spliceStackStr == nil { return result, resBl } result = its.spliceStackStr[its.stackTop] its.stackTop-- resBl = true } } return result, resBl } //看一下棧頂的數值,不是彈出資料 func (its *stack) LookTopVal() (interface{}, bool) { val, bl := its.Pop() if bl{ its.stackTop++ } return val, bl } //獲取到當前棧的切片資訊 返回結果只可能是[]float32 或者[]string 或者nil 的切片資訊 func (its *stack) GetStackInfo() interface{} { var topNu = its.stackTop if topNu == -1 { return nil } var resVal interface{} if its.stackType == 1 { sliceInt := make([]float32, topNu+1) for idx := 0; idx <= topNu; idx++ { sliceInt[idx] = its.spliceStackFloat[topNu-idx] } resVal = sliceInt } else { sliceStr := make([]string, topNu+1) for idx := 0; idx <= topNu; idx++ { sliceStr[idx] = its.spliceStackStr[topNu-idx] } resVal = sliceStr } return resVal }