完成如下功能:
(1)初始化栈s;
(2)判断栈s是否非空;
(3)依次进栈元素a,b,c,d,e
(4)判断栈s是否非空;
(5)输出栈长度;
(6)输出从栈顶到栈底元素;
(7)输出出栈序列;
(8)判断栈s是否非空;
(9)释放栈。
代码:
#include"iostream"
#include"malloc.h"
using namespace std;
#define MaxSize 50
typedef struct{
char data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack *&s){
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
bool StackEmpty(SqStack *s){
return(s->top==-1);
}
bool Push(SqStack *&s,char e){
if(s->top==MaxSize-1)
return false;
s->top++;
s->data[s->top]=e;
return true;
}
int StackLength(SqStack *s){
return (s->top+1);
}
bool Pop(SqStack *s){
int i;
i=s->top;
if(s->top==-1)
return false;
else{
for(;s->top!=-1;s->top--)
{
cout << s->data[s->top] << " " ;
}
s->top=i;
cout << endl;
return true;
}
}
bool Get(SqStack *&s){
if(s->top==-1)
return false;
else{
for(;s->top!=-1;s->top--)
{
cout << s->data[s->top] << " " ;
}
cout << endl;
return true;
}
}
void DestroyStack(SqStack* &s){
free(s);
}
void main()
{
SqStack* s;
InitStack(s);
cout << StackEmpty(s) << endl;
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
cout << StackEmpty(s) << endl;
cout << StackLength(s) << endl;
Pop(s);
Get(s);
cout << StackEmpty(s) << endl;
DestroyStack(s);
}