zoukankan      html  css  js  c++  java
  • 【数据结构】堆栈

    堆栈 满足先进后出原则

    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
    “年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
  • 相关阅读:
    Java数组的内存结构
    2014.11.9--最近的小感悟
    十一两天感悟
    Are you happiness
    Are you busy?
    Lesson 81-82 Are they true
    Lesson 79-80 People are getting sick
    Lesson 77-78 Socially Discriminated Against
    Lesson 75-76 Shopping on the web
    更新单点,求区间—— luogu 3374
  • 原文地址:https://www.cnblogs.com/jzsg/p/10889854.html
Copyright © 2011-2022 走看看