栈的相关基本知识
栈也是一种线性表,但是栈是一种操作受限的线性表,因此也可称它为限定性的数据机构。
栈是限定仅在表尾进行插入或删除操作的线性表。栈的表尾为它的栈顶,表头为它的栈底。
先进入栈的后出栈,后进入栈的先出栈。所以,栈被称为后进先出的线性表。
顺序栈基本操作的实现:
#include<stdio.h>
#include<stdlib.h>
#define INIT_STACKSIZE 5
#define INCREMENTSIZE 5
typedef struct{
int *base;
int *top;
int stacksize;
}SqStack;
int Init_Stack(SqStack &S);
int Stack_Empty(SqStack S);
int Push(SqStack &S,int e);
void Get_Top(SqStack S,int &e);
void Pop(SqStack &S,int &e);
int Clear_Stack(SqStack &S);
int main()
{
SqStack S;
int e;
//构造一个顺序栈
if(Init_Stack(S)==1)
printf("构造一个顺序栈成功!\n");
//判断栈空
if(Stack_Empty(S)==1)
printf("此时栈为空!\n");
//向栈中压入6个数据元素
for(int i=1;i<=7;i++)
{
Push(S,i);
}
//查看栈顶元素
Get_Top(S,e);
printf("栈顶元素为:%d\n",e);
//删除栈顶元素并且打印它的值
Pop(S,e);
printf("删除栈顶元素成功,其值为:%d\n",e);
//再次查看栈顶元素
Get_Top(S,e);
printf("栈顶元素为:%d\n",e);
//清空栈
if(Clear_Stack(S)==1)
printf("清空栈成功!\n");
}
int Clear_Stack(SqStack &S)
{
S.top=S.base;
if(S.base==S.top)
return 1;
else
return 0;
}
void Pop(SqStack &S,int &e)
{
if(S.top==S.base)
exit(-1);
else
e=*(--S.top);
}
void Get_Top(SqStack S,int &e)
{
if(S.base==S.top)
exit(-1);
else
e=*(S.top-1);
}
int Push(SqStack &S,int e)
{
if(S.top-S.base>=S.stacksize)
{
S.base=(int *)realloc(S.base,(S.stacksize+INCREMENTSIZE)*sizeof(int));
if(!S.base)
exit(-1);
S.top=S.base+S.stacksize;
S.stacksize+=INCREMENTSIZE;
}
*S.top++=e;
}
int Stack_Empty(SqStack S)
{
if(S.base==S.top)
return 1;
else
return 0;
}
int Init_Stack(SqStack &S)
{
S.base=(int *)malloc(INIT_STACKSIZE*sizeof(int));
if(!S.base)
exit(-1);
S.top=S.base;
S.stacksize=INIT_STACKSIZE;
return 1;
}