Sequential stack (stack operations)

describe

 

Create a sequential stack, which can complete the stack initialization, push stack, pop stack, get the top element of the stack, destroy the stack and other operations. 

Part of the code has been given, please complete it. Please do not include the given code when submitting.

 

enter

 

The input data consists of the following commands:

(1) push x: push x onto the stack

(2) pop: pop the stack

(3) top: Get the top element of the stack

Each command occupies one line and ends with EOF.

 

output

 

When pop is executed, the popped element is output, and when top is executed, the top element of the stack is output.

When the stack is empty, Empty needs to be output.

It can automatically expand when the stack is full.

 

sample input

 

push 1
push 2
top
pop
pop
pop

 

Sample output

 

2
2
1
Empty

Code test:

#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);
}

intmain ()
{
    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\n");
            else
                printf("%d\n", x);
        }
        else
        {
            res = Pop(&s, &x);
            if(res==0)
                printf("EMPTY\n");
            else
                printf("%d\n", x);
        }
    }
    Destroy(&s);
    return 0;
}
View Code

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325105420&siteId=291194637