1、栈的概念:栈是限定仅在表尾进行插入和删除操作的线性表
需要注意的几个问题:首先栈是一个线性表,栈元素之间具有线性关系,即有前驱和后继关系,只不过它是一种特殊的线性表而已。这里的表尾指的是栈顶而不是栈底。表的特殊之处在于限制了这个线性表插入和删除位置,它只能在栈顶进行。它是一种 LIFO(Last In First Out) 线性表。
栈的基本操作入下图
2、栈的基本操作
#include<stdio.h>
#include<stdlib.h>
/*4.4栈的顺序存储结构及实现(数组的方法实现)P79*/
#define bool char
#define true 1
#define false 0
#define MaxSize (50)
typedef int ElemType;
typedef struct{
ElemType data[MaxSize]; /*定义一个数组用于储存栈元素*/
int top; /*用于栈顶指针*/
}SqStack;
/*******顺序栈的初始化********/
bool InitStack(SqStack *S)
{
S->top=-1; //初始化栈顶指针
}
/*******栈是否为空********/
int StackEmpty(SqStack S)
{
if(S.top=-1){
return true;
}
else
return false;
}
/*******入栈(压栈)的操作********/
bool StackPush(SqStack *S,ElemType e)
{
if(S->top==MaxSize-1) //如果栈为满无法完成入栈操作(注意是两个==)
{
printf("Stack in ERROR \n");
return false;
}
S->top++;
S->data[S->top]=e; //或者 S->data[++S->top]=e;
return true;
}
/*******出栈的操作********/
int StackPop(SqStack *S,ElemType *e)
{
if(S->top==-1) //如果栈为空无法完成出栈操作
{
printf("Stack in NULL \n");
return 0;
}
else
*e=S->data[S->top]; //注意这里是返回一个指针
S->top--;
return 1;
}
/*******读出栈顶元素********/
int StackGettop(SqStack *S,ElemType *e)
{
if(NULL==S->data)
return 0;
*e=S->data[S->top];
return true;
}
int main( void)
{
SqStack S;
InitStack(&S);
StackPush(&S,1);
StackPush(&S,2);
StackPush(&S,3);
StackPush(&S,4);
StackPush(&S,5);
ElemType X=0;
for(int i=0;i<=S.top;i++)
{
printf("i=%d \n",i);
StackGettop(&S,&X);
printf("Gettop X=%d \n",X);
StackPop(&S,&X);
printf("Stackpop X=%d\n",X);
}
system("pause");
return 1;
}