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
  • 相关阅读:
    自定义checkbox样式
    自定义select样式
    jsonp
    I/O复用 poll简介
    DOS和DDOS攻击
    TCP状态转换图解析
    Makefile入门
    I/O复用select 使用简介
    替换文本内容
    share memory
  • 原文地址:https://www.cnblogs.com/momo-88/p/8974874.html
Copyright © 2011-2022 走看看