【数据结构】堆栈

堆栈 满足先进后出原则

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
相关文章