TOJ 数据结构实验--静态顺序栈

描述

创建一个顺序栈(静态),栈大小为5。能够完成栈的初始化、入栈、出栈、获取栈顶元素、销毁栈等操作。 

顺序栈类型定义如下:

typedef struct
 {  int data[Max];
    int top;
  }SqStack;

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

int main()
{
    SqStack s;
    char ss[10]; 
    int x, sta; 
    InitStack(&s); 
    while(scanf("%s", ss)!=EOF) 
    {
        if(strcmp(ss, "push")==0)
        {
            scanf("%d", &x);
            sta=Push(&s, x);
            if(sta==0)
                printf("FULL\n"); 
        }
        else if(strcmp(ss, "top")==0)
        {
            sta= GetTop(s, &x); 
            if(sta==0)
                printf("EMPTY\n"); 
            else
                printf("%d\n", x);
        }
        else
        {
            sta = Pop(&s, &x);
            if(sta==0)
                printf("EMPTY\n"); 
            else
                printf("%d\n", x);
        } 
    }
    return 0;
}

输入

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

1)push x:将x压入栈

2)pop:出栈

3)top:获取栈顶元素

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

输出

当执行push操作时元素入栈,若栈满,输出FULL。

当执行pop时输出出栈的元素,当栈为空时,需要输出EMPTY。

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

样例输入

 push
1
push
2
push
3
push
4
push
5
push
6
pop
top
pop
pop
pop
pop
pop

样例输出

FULL
5
4
4
3
2
1
EMPTY

#include<string.h>
#define Max 5
#include <stdio.h>
typedef struct
 {  int data[Max];
    int top;
  }SqStack;
int  StackEmpty(SqStack s)
{//判断栈空
    if(s.top==-1)
        return 1;
    else return 0;
}
void InitStack(SqStack *s)
{//初始化栈
    s->top=-1;//空栈
}
int  Push(SqStack *s,int x)
{//进栈
    if(s->top==Max-1)//栈满
        return 0;
    else {
        s->top++;
        s->data[s->top]=x;
        return 1;
    }
}
int Pop(SqStack *s,int *x)
{//删除栈顶元素
    if(StackEmpty(*s))
        return 0;
    else{
        *x=s->data[s->top];
        s->top--;
        return *x;
    }
}
int GetTop(SqStack s,int *x)
{//获取栈顶元素
    if(StackEmpty(s))
    {
        return 0;
    }
    else{
        *x=s.data[s.top];
        return *x;
    }
}
int main()
{
    SqStack s;
    char ss[10];
    int x, sta;
    InitStack(&s);
    while(scanf("%s", ss)!=EOF)
    {
        if(strcmp(ss, "push")==0)
        {
            scanf("%d", &x);
            sta=Push(&s, x);
            if(sta==0)
                printf("FULL\n");
        }
        else if(strcmp(ss, "top")==0)
        {
            sta= GetTop(s, &x);
            if(sta==0)
                printf("EMPTY\n");
            else
                printf("%d\n", x);
        }
        else
        {
            sta = Pop(&s, &x);
            if(sta==0)
                printf("EMPTY\n");
            else
                printf("%d\n", x);
        }
    }
    return 0;
}

 

猜你喜欢

转载自www.cnblogs.com/baobao2201128470/p/8909731.html