• 顺序栈 (栈操作)


    描述

     

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

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

     

    输入

     

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

    (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
  • 相关阅读:
    Word pair Hu
    [bzoj1601] 灌水
    小木棍
    雇佣计划
    [Luogu1282] 多米诺骨牌
    [Luogu1216] 数字三角形
    [Luogu1734] 最大约数和
    [NOIp2008] 传纸条
    [Luogu1325] 雷达安装
    nginx
  • 原文地址:https://www.cnblogs.com/momo-88/p/8974874.html
Copyright © 2020-2023  润新知