Go語言棧定義及相關方法實現

來源:互聯網
上載者:User

標籤: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語言棧定義及相關方法實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.