编写一个程序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;
}
本文介绍了如何使用自定义的顺序栈数据结构进行字符序列的入栈和逆序输出操作。首先,我们创建了一个顺序栈结构并实现了初始化、入栈、出栈、获取栈顶元素和判断栈空的基本操作。接着,通过主程序演示了如何读取用户输入的字符,逆序存储在栈中,最后逐个弹出并输出。

670

被折叠的 条评论
为什么被折叠?



