Open judge 顺序栈

全局题号 9747
描述
编写一个程序实现顺序栈(假设栈中元素类型为char)的各种基本运算,并在此基础上设计一个主程序完成如下功能:

(1)初始化顺序栈S;

(2)判断顺序栈S是否为空;

(3)依次进栈元素a,b,c,d,e;

(4)判断顺序栈S是否为空;

(5)输出顺序栈长度;

(6)输出从栈顶到栈底的元素;

(7)输出出栈序列;

(8)判断顺序栈S是否为空;

(9)释放顺序栈。

输入
两行数据,第一行是入栈字符数据的个数,第二行是具体入栈的字符数据。
输出
按照程序要求输出。
样例输入
5
a b c d e
样例输出
yes
no
5
e d c b a
e d c b a
yes

代码:

# include <stdio.h>
# include <stdlib.h>
#define ElemType char
#define maxsize 100
typedef struct {
    ElemType data[maxsize];
    int top;
}SqStack;
void InitStack(SqStack*& s)
{
    s = (SqStack*)malloc(sizeof(SqStack));
  if(s!=NULL) s->top = -1;
}

void DestroyStack(SqStack*& s)
{
    free(s);
}

bool StackEmpty(SqStack*& s)
{
    return (s->top == -1);
}

bool Push(SqStack*& s, ElemType e)
{
    if (s->top == maxsize - 1)
        return false;

    s->top++;
    s->data[s->top] = e;
    return true;
}

bool Pop(SqStack*& s, ElemType &e)
{
    if (s->top == -1)
        return false;

    e = s->data[s->top];
    s->top--;
    return true;
}

bool GetTop(SqStack* s, ElemType &e)
{
    if (s->top == -1)
        return false;

    e = s->data[s->top];
    return true;
}

int main()
{
    int i=0,m,k=0;
    SqStack*s;
    InitStack(s);
    char a[maxsize],e;
    scanf("%d\n",&m);

    for(i = 0;i < m; i++){
       if(i!=m-1) scanf("%c ",&a[i]);
       else scanf("%c",&a[i]);
    }


    
    if(StackEmpty(s)){
        printf("yes\n");
    }else{
        printf("no\n");
    }
    
    for(i = 0;i < m; i++){
        Push(s,a[i]);
    }

    if(StackEmpty(s)){
        printf("yes\n");
    }else{
        printf("no\n");
    }

    printf("%d\n",s->top+1);

    for(i = m-1;i >= 0; i--){
       if(i!=0) printf("%c ",s->data[i]);
       else      printf("%c",s->data[i]);   
    }


    printf("\n");

    for(i = 0;i < m; i++){
        Pop(s,e);
      if(i!=m-1)  printf("%c ",e);
      else printf("%c",e);
    }
    printf("\n");

    if(StackEmpty(s)) printf("yes\n");
    else printf("no\n");

    DestroyStack(s);

    system("pause");
    return 0;

}

记得点赞哦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值