微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【数据结构】堆栈

堆栈 满足先进后出原则

1、python 描述

分享图片

# 堆栈 先进后出原则
MAXSTACK = 10
global stack
stack = [None] * MAXSTACK
top = -1


def is_empty():
    if top == -1:
        return True
    else:
        return False


def push(data):
    global top
    global MAXSTACK
    global stack
    if top >= MAXSTACK - 1:
        print("堆栈已满,无法加入")
    else:
        top += 1
        stack[top] = data


def pop():
    global top
    global stack
    if is_empty():
        print("堆栈是空的")
    else:
        print("弹出元素为: %d" % stack[top])
        top = top - 1


if __name__ == "__main__":
    i = 0
    while i < 10:
        i += 1
        push(i)
        
pop()
View Code

 2、go 描述

分享图片

package test

import (
"fmt"
"testing"
)

const MAX_CAPACITY int = 10 // 定义栈容量
var stack [MAX_CAPACITY]interface{}
var top = -1 //栈顶元素下标


func isEmpty() bool{
    if top == -1 {
        return true
    }
    return false
}

func push(data interface{}){
    if top > MAX_CAPACITY-1 {
        fmt.Println("栈容量已满,无法push")
    }else {
        top ++
        stack[top] = data
    }
}


func pop(){
    if isEmpty() {
        fmt.Println("栈是空的")
    }else {
        fmt.Println("弹出元素为: ",stack[top])
        top --
    }
}

func Test_Stack(t *testing.T)  {
    for i:=0;i<5;i++{
        push(i)
    }
    fmt.Println(stack)
    pop()
}
View Code

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐