栈的操作算法实现(数据结构)
1.实验目的
验证性实验:实现顺序栈各种基本运算的算法掌握栈的存储结构的表示和实现方法。
目的:领会顺序栈存储结构和掌握顺序栈中各种基本运算算法设计。
2.实验内容
验证性实验内容:编写一个程序sqstack.cpp,实现顺序栈(假设栈中元素类型ElemType为char的各种基本运算,并在此基础上设计一个程序exp3-1.cpp。
实现如下功能:
(1)初始化栈s。
(2)判断栈s是否非空。
(3)依次进栈元素a、b、c、d、e。
(4)判断栈s是否非空。
(5)输出出栈序列。
(6)判断栈s是否非空。
(7)释放栈。
3.具体代码实现及解释
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;//栈指针
}SqStack; //声明顺序站类型
void InitStack(SqStack *&s)//初始化顺序站
{
s=(SqStack *)malloc(sizeof(SqStack));
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;
}
//#include "sqstack.cpp"//包含顺序站的基本运算算法
bool GetTop(SqStack *s,ElemType &e)
{
if(s->top==-1)
return false;
e=s->data[s->top];
return true;
}
int main()
{
ElemType e;
SqStack *s;
printf("顺序栈s的基本运算如下:");
printf("(1)初始化栈s\n");
InitStack(s);
printf("(2)栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(3)依次进栈元素a,b,c,d,e\n");
Push(s,'a');
Push(s,'b');
Push(s,'c');
Push(s,'d');
Push(s,'e');
printf("(4)栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(5)出栈序列:");
while(!StackEmpty(s))
{
Pop(s,e);
printf("%c ",e);
}
printf("\n");
printf("(6)栈为%s\n",(StackEmpty(s)?"空":"非空"));
printf("(7)释放栈\n");
DestroyStack(s);
return 1;
}
原文地址:https://blog.csdn.net/m0_61903191/article/details/142798226
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!