Problem D: 栈的基本运算(栈和队列)
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 43 Solved: 15
[Submit][Status][Web Board]
Description
编写一个程序,实现顺序栈的各种基本运算,主函数已给出,请补充每一种方法。
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;
 }
  Input
输入五个元素a,b,c,d,e;请根据题目编写算法。
Output
Sample Input
abcde Sample Output
空
非空
栈的长度为5
edcba
edcba
非空 HINT
请使用C++编译并提交
#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= new SqStack; s->top=-1; 
} 
bool StackEmpty(SqStack *s) 
{ return(s->top==-1); 
} 
bool Push(SqStack *&s,char e) 
{ if(s->top==SizeMax-1)return false; s->top++; s->data[s->top]=e; return true; 
} 
int Length(SqStack*s) 
{ return(s->top+1); 
} 
bool PrintStack(SqStack *s) 
{ int i,e,a; a=s->top; if(s->top==-1)return false; for(i=-1;i<s->top;i++) { e=s->data[a]; a--; printf("%c",e); } printf("\n"); return true; 
} 
bool Print(SqStack *&s) 
{ int i,e,a; a=s->top; if(s->top==-1)return false; for(i=-1;i<s->top;i++) { e=s->data[a]; a--; printf("%c",e); } printf("\n"); return true; 
} 
void DestroyStack(SqStack *&s) 
{ delete(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; 
}