编写一个程序sqstack.h,实现顺序栈的各种基本运算。在此基础上,给出将从键盘输入的字符序列逆置输出的算法。
sqstack.h
#include<iostream.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
} SqStack;
void InitStack(SqStack *&s)
{
s=new SqStack;
s->top=-1;
}
int Push(SqStack *&s,ElemType e)//入栈
{
if(s->top==MaxSize-1)
return 0;
s->top++;
s->data[s->top]=e;
return 1;
}
int Pop(SqStack *&s,ElemType &e)//出栈
{
if(s->top==-1)
{ cout<<"溢出";
return 0;}
e=s->data[s->top];
s->top--;
return e;
}
int GetTop(SqStack *s,ElemType &e)//获取栈顶元素
{
if(s->top==-1)
{ return 0;
e=s->data[s->top];}
cout<<e;
return 1;
}
int StackEmpty(SqStack *s)//判断栈是否为空
{
return(s->top==-1);
}
void DispStack(SqStack *s)//输出栈的元素
{
int i;
for(i=s->top;i>=0;i--)
cout<<s->data[i];
cout<<endl;
}
主程序:
#include"sqstack.h"
#include<stdio.h>
typedef char ElemType;
void main()
{
int i,n;
cout<<"请输入字符长度:";
cin>>n;
cout<<"请输入字符串:";
SqStack *s;
ElemType e;
InitStack(s);
for(i=1;i<=n;i++)
{cin>>e;
Push(s,e);}
cout<<"逆序的结果为:";
while(!StackEmpty(s))
{
Pop(s,e);
cout<<e;
}
cout<<endl;
}
版权声明:本文为lucario1原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。