栈的顺序实现及基本操作
顺序存储类型描述
#define MAXSIZE 10
typedef struct{
int data[MAXSIZE]; //存放栈中元素
int top; //栈顶指针
}SqStack;
注意事项
- 在操作前一定要进行初始化,本次实现过程中,最开始写了初始化函数,没有调用,导致栈的长度和存储的数据一直不对
- 顺序栈的出栈操作,只是逻辑上将指针下移一位,里面的数据并未删除
- 初始化有两种操作,一种是top=-1(本文就是这种),一种是top=0,这两种操作的判空条件不同,且在进行入栈、出栈时的操作也不一样
- ++i和i++不是一类,i++是先返回再+1,++i是先+1再返回。代码中有这两处不同的比较
源代码如下
#include<stdio.h>
#define MAXSIZE 10
typedef struct{
int data[MAXSIZE];
int top;
}SqStack;
void InitStack(SqStack &stack)
{
stack.top=-1;
}
bool StackEmpty(SqStack stack)
{
if(stack.top==-1)
return true;
return false;
}
bool StackFull(SqStack stack)
{
if(stack.top==MAXSIZE-1)
return true;
return false;
}
bool Push(SqStack &stack,int e)
{
if(StackFull(stack))
return false;
// stack.top+=1;
// stack.data[stack.top]=e;
stack.data[++stack.top]=e;
return true;
}
bool Pop(SqStack &stack,int &e)
{
if(StackEmpty(stack))
return false;
// e=stack.data[stack.top];
// stack.top-=1;
e=stack.data[stack.top--];
return true;
}
bool GetTop(SqStack stack,int &top)
{
if(StackEmpty(stack))
return false;
top=stack.data[stack.top];
return true;
}
int GetLen(SqStack stack)
{
if(StackEmpty(stack))
return 0;
return stack.top+1;
}
bool PrintStack(SqStack stack)
{
if(StackEmpty(stack))
return false;
printf("栈为:");
while(stack.top!=-1)
{
printf("\t%d\n ",stack.data[stack.top]);
stack.top--;
}
printf("\n");
return true;
}
int main()
{
SqStack stack;
int pop=-1,top=-1;
InitStack(stack);
for(int i=0;i<11;i++)
{
if(!Push(stack,i))
printf("Stack is full\n");
}
printf("len:%d\n",GetLen(stack));
if(!PrintStack(stack)){
printf("栈为空!无法打印\n");
}
if(GetTop(stack,top))
printf("栈顶元素:%d\n",top);
if(Pop(stack,pop))
printf("pop e:%d\n",pop);
if(Pop(stack,pop))
printf("pop e:%d\n",pop);
if(!PrintStack(stack)){
printf("栈为空!无法打印\n");
}
return 0;
}
运行结果
结束语:It"s been a long day…加油