顺序栈操作--数据结构(C++)版

最近学习数据结构,一开始接触感觉好难,颓废了一段时间,后来又重新翻开学习,突然感觉到很大的兴趣。对这些代码的运用都有了 一些新的认识。下面简单的讲述下最新学到的顺序栈,不知道大家学习的时候会不会有感觉,书上写的那么简单,但是我写的都是不对,不是这里有错就是那里有错,最后还是攻克了,心理慢慢地成就感。

题目大概:输入一串整数,如果 该数不等于-1,就进栈,若是等于-1,则输出栈顶整数并出栈。同时算法给出应对异常的情况。

代码实现

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAX 100
typedef int ElemType;
typedef struct
{
ElemType *top;
ElemType *base;
int stacksize;
}SqStack;
//给予栈初始化
bool InitStack(SqStack &S)
{
S.base=new ElemType[MAX];
if(!S.base) return false;
S.top=S.base;
S.stacksize=MAX;
return true;

}
//输出栈顶元素
char GetTop(SqStack S)
{
if(S.top!=S.base)
printf("获取栈顶数:%d ",*(S.top-1));
}
//入栈
bool Pop(SqStack &S,ElemType &e)
{
if(S.top==S.base) return false;
e=*--S.top;
printf("出栈数:%d ",e);
return true;
}
//出栈
bool Push(SqStack &S,ElemType &e)
{
if(S.top-S.base==S.stacksize) return false;
if(e==-1)
{
GetTop(S);
Pop(S,e);
return true;
}
*S.top++=e;
printf("入栈数:%d ",e);
return true;
}
//判断是否为空
int IsEmpty(SqStack S)
{
if(S.top==S.base) return 1;
else
return 0;
}
//判断是否为满
int IsFull(SqStack S)
{
if(S.top-S.base==S.stacksize) return 1;
else
return 0;
}
//销毁
int DestroyStack( SqStack &S )
{
if( S.base )
{
delete S.base ;
S.stacksize = 0;
S.base = S.top = NULL;
}
return 1;
}

主函数部分
int main()
{
SqStack s;
ElemType e;
int i;
printf("(1)初始化 ");
InitStack(s);
printf("初始化是否成功:%s ",(InitStack(s)?"是":"否"));
printf("(2)PUSH: ");
for( i = 0; i < 5;i++ )
{
e=i;
Push( s, e );
}
printf("(3)测试:当输入数为-1时 ");
e=-1;
Push( s, e );
printf("(4)输出栈是否为空为 %s ",(IsEmpty(s)?"空":"非空"));
printf("(5)输出栈是否为满为 %s ",(IsFull(s)?"满":"非满"));
printf("(6)销毁栈 %s ",(DestroyStack(s)?"成功":"失败"));
return 0;
}

问题:

1.base opera of -> has non-pointer type ...

有时候编译软件在用->就报错,但是修改为S.base就为正确了

2.还有 一点符号问题&与*是有区别了,注意看

3.剩下的问题就不列举了

原文地址:https://www.cnblogs.com/skylarzhan/p/5986458.html