栈其实是一种特殊的线性表,是只允许在尾部插入,和删除操作的一种线性表。我们把允许插入的一端称为栈顶(top),另一段为栈底。不含任何元素的栈为空栈(top=-1,top始终是指向栈顶的)。既然是特殊的线性表,我们把删除和插入操作改名为pop和push,一般称为出栈和入栈。本次笔记记录的是栈的顺序存储结构以及初始化、出栈、入栈、清空、遍历、获取栈长度、获取栈顶元素等操作。
具体代码如下:
#include "iostream"
using namespace std;
#define OK 1
#define ERROR 0
#define MAXSIZE 100
#define OK 1
#define ERROR -1
typedef int Status ;
typedef int ElemType;
typedef struct SqStack
{
ElemType data[MAXSIZE];
int top;//栈顶指针,值为-1表示空栈
}SqStack;
//栈的初始化
Status InitStack(SqStack &S)
{
S.top = -1;
return OK;
}
//出栈
Status pop(SqStack &S,ElemType &e)
{
if (S.top == -1)
return ERROR;
e = S.data[S.top];//将栈顶元素赋值为e
S.top--;//栈顶指针减1
return OK;
}
//进栈
Status push(SqStack &S, ElemType e)
{
if (S.top==MAXSIZE-1)
return ERROR;
S.top++;//栈顶指针加1
S.data[S.top] = e;//元素进栈
return OK;
}
//清空栈
Status clear(SqStack &S)
{
S.top = -1;
return OK;
}
//获取栈顶元素
Status GetElem(SqStack &S,ElemType &e)
{
if (S.top == -1)
return ERROR;
e = S.data[S.top];//因为top是栈顶指针,下标为top的元素即为栈顶元素
return OK;
}
//获取栈的长度,即栈中的元素个数
int Length(SqStack S)
{
if (S.top == -1)
return 0;
else
return S.top + 1;
}
//遍历栈中的元素
Status Visit(SqStack S)
{
if (S.top == -1)
{
cout << "空栈" << endl;
return ERROR;
}
for (int i = 0; i <= S.top; i++)
{
cout << S.data[i]<<" ";
}
cout << endl;
return OK;
}
int main()
{
SqStack S;
int e;
InitStack(S);
for (int i = 0; i <= 5; i++)
{
push(S, i);
}
cout << "栈中的元素:";
Visit(S);
int len = Length(S);
cout << "栈的长度为:" << len << endl;
GetElem(S, e);
cout << "栈顶元素为:" << e << endl;
pop(S, e);
cout << "pop:" << e << endl;
cout << "栈中的元素:";
Visit(S);
cout << "清空栈后:" << endl;
clear(S);
Visit(S);
getchar();
return 0;
}