3004: 栈的基本运算(栈和队列)
时间限制: 1 Sec 内存限制: 128 MB提交: 32 解决: 10
题目描述
编写一个程序,实现顺序栈的各种基本运算,主函数已给出,请补充每一种方法。
1、初始化栈s;
2、判断栈s是否非空;
3、进栈一个元素;
4、判读栈s是否非空;
5、输出栈长度;
6、输出从栈顶到栈元素;
7、输出出栈序列;
8、判断栈s是否非空;
9、释放栈;
数据元素类型定义为
typedef char ElemType;
顺序栈的定义为
typedef struct
{
ElemType data[SizeMax];
int top;
}SqStack;
主函数:
int main()
{
SqStack *s;
InitStack(s); //初始化栈
if(StackEmpty(s))printf("空\n"); //判断栈是否为空
else printf("非空\n");
ElemType a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
Push(s,a); //入栈
Push(s,b);
Push(s,c);
Push(s,d);
Push(s,e);
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
printf("栈的长度为%d\n",Length(s)); //输出栈的长度
PrintStack(s); //输出从栈顶到栈底的元素
Print(s); //输出出栈序列
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
DestroyStack(s); //释放栈
return 0;
}
输入
输入五个元素a,b,c,d,e;请根据题目编写算法。
输出
样例输入
abcde
样例输出
空
非空
栈的长度为5
edcba
edcba
非空
迷失在幽谷中的鸟儿,独自飞翔在这偌大的天地间,却不知自己该飞往何方……
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define SizeMax 105
typedef char ElemType;
typedef struct
{
ElemType data[SizeMax];
int top;
} SqStack;
void InitStack(SqStack *&s)
{
s=(SqStack*)malloc(sizeof(SqStack));
memset(s->data,0,sizeof(SqStack));
s->top=-1;
}
int StackEmpty(SqStack *s)
{
return s->top==-1;
}
void Push(SqStack *&s,ElemType x)
{
s->top++;
s->data[s->top]=x;
}
int Length(SqStack *s)
{
return s->top+1;
}
void PrintStack(SqStack *s)
{
for(int i=(int)strlen(s->data)-1; i>=0; i--)
printf("%c",s->data[i]);
printf("\n");
}
void Print(SqStack *s)
{
PrintStack(s);
}
void DestroyStack(SqStack *&s)
{
free(s);
}
int main()
{
SqStack *s;
InitStack(s); //初始化栈
if(StackEmpty(s))printf("空\n"); //判断栈是否为空
else printf("非空\n");
ElemType a,b,c,d,e;
cin>>a>>b>>c>>d>>e;
Push(s,a); //入栈
Push(s,b);
Push(s,c);
Push(s,d);
Push(s,e);
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
printf("栈的长度为%d\n",Length(s)); //输出栈的长度
PrintStack(s); //输出从栈顶到栈底的元素
Print(s); //输出出栈序列
if(StackEmpty(s))printf("空\n");
else printf("非空\n");
DestroyStack(s); //释放栈
return 0;
}