栈的应用实验
栈的应用
一、实验目的
1、掌握栈的基本概念和后入先出的基本特征。
2、掌握栈的基本操作,包括:栈的初始化、销毁、入栈和出栈操作。
二、实验内容
1、采用顺序表初始化空间大小为 50 个字符的栈。
2、完成下列操作,其中 S 为栈,x,y 为字符型变量。
x= "c";
y= "k";
Push(S,x);
Push(S, "a");
Push(S,y);
Pop(S,x);
Push(S, "t");
Push(S,x);
Pop(S,x);
Push(S, "s");
while (!SEmpty(S))
{
Pop(S,y);
printf( “%c”,y);
}
printf( “%c”,x);
我自己写的
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXSIZE 50
typedef char SElemType;
typedef int Status;
typedef struct
{
SElemType* base;
SElemType* top;
int stacksize;
}SqStack;
Status InitStack(SqStack& S)
{
S.base = (SElemType*)malloc(MAXSIZE * sizeof(SElemType));
S.top = S.base;
return 1;
}
Status Push(SqStack& S, SElemType& e)
{
*S.top++ = e;
return 1;
}
Status Pop(SqStack& S, SElemType& e)
{
e = *--S.top;
return 1;
}
SElemType SEmpty(SqStack* S)
{
if (S->top == S->base)
return 1;
else
return 0;
}
int main()
{
SqStack S;
InitStack(S);
char x = 'c';
char y = 'k';
char m = 'a';
char n = 't';
char q = 's';
Push(S, x);
Push(S, m);
Push(S, y);
Pop(S, x);
Push(S, n);
Push(S, x);
Pop(S, x);
Push(S, q);
while (!SEmpty(&S))
{
Pop(S, y);
printf("%c", y);
}
printf("%c", x);
}
根据自己在b站上学习的一些知识,结合书本写的代码。。。
我搞了很久,遇到了一些问题
1.无语,VS总是这样,不能立即运行新的代码
2.
后来我经过对比,发现我没有初始化一个空栈,导致错误
3.
这个改为char很重要,不要typedef int SElemType,我一开始就这么做,然后错了,这关系到下面的赋值,会很麻烦
4.还有这里我实在想不懂
对比别人的代码,可能S定义有问题
5.我漏写了一个判断栈空的函数,然后也运行失败了