zoukankan      html  css  js  c++  java
  • 算法导论8:数据结构——栈 2016.1.8

      栈在暑假的时候接触过了,当时还写了个计算器,用的中缀表达式后缀表达式的栈操作。

        http://www.cnblogs.com/itlqs/p/4749998.html

      今天按照算法导论上的讲解规范了一下代码。主要是栈的初始化、判断空栈、入栈、出栈、遍历栈。

    #include<stdio.h>
    
    #define MAXTOP 10 
    
    struct _stack {
        int top;
        int num[MAXTOP+1];
    }s;
    
    void init(struct _stack &S)
    {
        S.top=0;
    }
    
    int sempty(struct _stack &S)
    {
        if (S.top==0) return 1;
        else return 0;
    }
    
    void push(struct _stack &S,int n)
    {
        if (S.top==MAXTOP) {
            printf("栈顶溢出,压栈失败!
    ");
        }
        else {
            S.top++;
            S.num[S.top]=n;
        }
    }
    
    int pop(struct _stack &S)
    {
        if (S.top==0) {
            printf("栈为空,弹出失败!
    ");
        }
        else {
            S.top--;
            return S.num[S.top+1];
        }
    }
    
    void showstack(struct _stack S)
    {
        while (!sempty(S)){
            int k=pop(S);
            printf("|%d|
    ",k);
        }
        printf("| |
    ");
        printf(" - 
    ");
    }
    
    int main()
    {
        int n;
        printf("1:初始化栈;2:入栈;3:出栈;4:退出。
    ");
        while (1) {
            int k;
            scanf("%d",&k);
            switch(k) {
                case 1:init(s); break;
                case 2:scanf("%d",&n); push(s,n); break;
                case 3:pop(s); break;
                case 4:return 0;
            }
            showstack(s);
        }
        return 0;
    }


    明天用链表写一写。

  • 相关阅读:
    Apache Spark 2.2.0 中文文档
    Apache Spark 2.2.0 中文文档
    Apache Storm 1.1.0 中文文档 | ApacheCN
    mysql生成随机字符串
    nginx的5个特点
    虚拟机网络配置
    (mapreduce题) 找出有共同好友的 users --好好玩
    activemq-5.15.10 启动不了
    mysql导出 Excel数据字典(全)
    WebStorm 免注册码
  • 原文地址:https://www.cnblogs.com/itlqs/p/5115152.html
Copyright © 2011-2022 走看看