/*使用静态数组定义顺序栈*/
#include<stdio.h>
#define MaxSize 10 //此静态数组的最大值即顺序栈最多可存放的数据个数
typedef struct
{
int data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &s); //初始化栈
bool StackEmpty(SqStack s); //判断栈空
bool Push(SqStack &s,int x); //入栈操作
bool Pop(SqStack &s,int &x); //出栈
bool GetTop(SqStack s,int &x); //读栈顶元素
void InitStack(SqStack &s)
{
s.top=-1; //初始化栈顶指针
return;
}
bool StackEmpty(SqStack s)
{
if(s.top==-1)
{
return true;
}
else
{
return false;
}
}
//新元素入栈
bool Push(SqStack &s,int x)
{
if(s.top==MaxSize-1) //判断栈是否满,若栈满则不能成功插入元素,返回错误
{
return false;
}
s.top=s.top+1;
s.data[s.top]=x;
return true;
}
//出栈操作
bool Pop(SqStack &s,int &x)
{
if(s.top==-1) //若栈空则没有元素可删除,返回错误
{
return false;
}
while(s.top!=-1)
{
x=s.data[s.top];
s.top=s.top-1;
printf("%d ",x);
}
printf("\n");
return true;
}
//读栈顶元素
bool GetTop(SqStack s,int &x)
{
if(s.top==-1)
{
return false;
}
x=s.data[s.top];
printf("栈顶元素为:%d\n",x);
return true;
}
int main(void)
{
SqStack s;
int x=0;
InitStack(s);
if(Push(s,3));//入栈操作
{
printf("入栈成功!\n");
}
Push(s,3);
Push(s,4);
Push(s,5);
Push(s,6);
GetTop(s,x); //读栈顶元素
printf("栈内元素出栈:");
Pop(s,x); //出栈
return 0;
}
此栈的示意图
另一种栈的表示方式
#include<stdio.h>
#define MaxSize 10
typedef struct
{
int data[MaxSize];
int top;
}SqStack;
bool StackEmpty(SqStack s);
void InitStack(SqStack &s);
bool Push(SqStack &s,int x); //入栈操作
bool Pop(SqStack &s,int &x); //出栈
bool GetTop(SqStack s,int &x); //读栈顶元素
bool StackEmpty(SqStack s)
{
if(s.top==0)
{
return true;
}
else
{
return false;
}
}
void InitStack(SqStack &s)
{
s.top==0;
return;
}
//新元素入栈
bool Push(SqStack &s,int x)
{
if(s.top==MaxSize) //判断栈是否满,若栈满则不能成功插入元素,返回错误
{
return false;
}
s.data[s.top]=x;
s.top=s.top+1;
return true;
}
//出栈操作
bool Pop(SqStack &s,int &x)
{
if(s.top==0) //若栈空则没有元素可删除,返回错误
{
return false;
}
while(s.top!=0)
{
s.top=s.top-1;
x=s.data[s.top];
printf("%d ",x);
}
printf("\n");
return true;
}
//读栈顶元素
bool GetTop(SqStack s,int &x)
{
if(s.top==0)
{
return false;
}
x=s.data[s.top-1];
printf("栈顶元素为:%d\n",x);
return true;
}
int main(void)
{
SqStack s;
int x=0;
InitStack(s);
if(Push(s,3));//入栈操作
{
printf("入栈成功!\n");
}
Push(s,3);
Push(s,4);
Push(s,5);
Push(s,6);
GetTop(s,x); //读栈顶元素
printf("栈内元素出栈:");
Pop(s,x); //出栈
return 0;
}
此栈示意图
两种栈的表示方式的区别在于一开始空栈时栈顶指针的指向,方式一的栈顶指针在空栈时指向栈底的下一个,方式二的栈顶指针在空栈时指向栈底。