全局题号 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;
}
记得点赞哦!