zoukankan      html  css  js  c++  java
  • 顺序栈 (栈操作)

    描述

     

    创建一个顺序栈,能够完成栈的初始化、入栈、出栈、获取栈顶元素、销毁栈等操作。 

    部分代码已经给出,请补充完整,提交时请勿包含已经给出的代码。

     

    输入

     

    输入数据由以下几种命令组成:

    (1)push x:将x压入栈

    (2)pop:出栈

    (3)top:获取栈顶元素

    每个命令占一行,以EOF结束。

    输出

     

    当执行pop时输出出栈的元素,当执行top时输出栈顶元素。

    当栈为空时,需要输出Empty。

    当栈满时能自动扩容。

    样例输入

     

    push 1
    push 2
    top
    pop
    pop
    pop

     

    样例输出

     

    2
    2
    1
    Empty

    代码测试:

    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #define Maxx 10000
    #define Maxy 1000
    
    typedef struct SqStack{
        int *base;
        int *top;
        int size;
    }SqStack;
    
    int InitStack(SqStack *s){
        s->base=(int *)malloc(Maxx*sizeof(int));
        if(!s->base) return 0;
        s->top=s->base;
        s->size=Maxx;
        return 1;
    }
    
    int Push(SqStack *s,int x){
        if((s->top-s->base)>s->size){
            s->base=(int *)realloc(s->base,(s->size+Maxy)*sizeof(int));
            if(!s->base) return 0;
            s->top=s->base+s->size;
            s->size+=Maxy;
        }
        *s->top++=x;
        return 1;
    }
    
    int GetTop(SqStack s,int *x){
        if(s.top==s.base) return 0;
        *x=*(s.top-1);
        return 1;
    }
    
    int Pop(SqStack *s,int *x){
        if(s->top==s->base) return 0;
        *x=*--s->top;
        return 1;
    }
    void Destroy(SqStack *s)
    {
        free(s->base);
    }
    
    int main()
    {
        SqStack s;
        InitStack(&s);
        char cmd[10];
        int x, res;
        while(scanf("%s", cmd)!=EOF)
        {
            if(strcmp(cmd, "push")==0)
            {
                scanf("%d", &x);
                Push(&s, x);
            }
            else if(strcmp(cmd, "top")==0)
            {
                res = GetTop(s, &x);
                if(res==0)
                    printf("EMPTY
    ");
                else
                    printf("%d
    ", x);
            }
            else
            {
                res = Pop(&s, &x);
                if(res==0)
                    printf("EMPTY
    ");
                else
                    printf("%d
    ", x);
            }
        }
        Destroy(&s);
        return 0;
    }
    View Code
  • 相关阅读:
    缓存雪崩与缓存穿透
    读取表中最大值
    使用vscode在谷歌上运行代码
    elment 中tree组件展开所有和收缩所有节点
    深度系统商店提示无法安装软件依赖错误
    诗词,理解,品论
    《45个十分钟读懂资本论》原文、适合朗读版和个人见解
    《论持久战》全文
    OSError: [WinError 126] 找不到指定的模块。
    C++ 获取序列最大(或最小)的 N 个元素
  • 原文地址:https://www.cnblogs.com/momo-88/p/8974874.html
Copyright © 2011-2022 走看看