顺序栈,即栈的顺序存储结构是利用一组地址连续的存储单元依次存取自栈底到栈顶的数据元素,同时附设指针top指示栈顶元素在顺序栈中的位置。
通常习惯将top=0表示空栈。
栈结构体
typedef int ElemType;
typedef struct SeqStack
{
ElemType data[MAXSIZE];
int top;
} SeqStack;
①初始化栈操作
//初始化栈操作
void initStack(SeqStack &s)
{
s.top=0;
}
②入栈操作
//入栈操作。如果成功返回,否则
//S:为要操作的栈
//x:为所要入栈的元素
Status push(SeqStack &s,ElemType x)
{
if(s.top==MAXSIZE -1)
return 0;
else
{
s.top++;
s.data[s.top]=x;
return 1;
}
}
③出栈操作
//出栈操作。如果成功返回,否则
//S:为所要操作的栈
//x:返回所要出栈的元素
Status pop(SeqStack &s,ElemType &x)
{
if(s.top== 0)
return 0;
else
{
x=s.data[s.top];
s.top--;
return 1;
}
}
④获得栈顶元素
//获取栈顶元素操作。如果成功,则返回,否则
//S:为所要操作的栈
//x:返回栈顶元素
Status getTop(SeqStack s,ElemType &x)
{
if(s.top== 0)
return 0;
else
{
x=s.data[s.top];
return 1;
}
}
⑤遍历栈
//遍历栈元素操作,按从栈顶到栈底的顺序遍历的栈中元素
//S:为所要遍历的栈
//visit:遍历过程所用的操作
void display(SeqStack &s)
{
for(int i=s.top;i>0;i--)
printf("%d ",s.data[i]);
printf("\n");
}
⑥栈是否为空
//判断栈是否为空,若空,返回真,否则返回假
int stackEmpty(SeqStack s)
{
if(s.top== 0)
return TRUE;
else
return FALSE;
}
主函数测试
#include <iostream>
#include <string.h>
#include <algorithm>
#include <cstdio>
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100
using namespace std;
typedef int Status;
typedef int ElemType;
typedef struct SeqStack
{
ElemType data[MAXSIZE];
int top;
} SeqStack;
//初始化栈操作
void initStack(SeqStack &s)
{
s.top=0;
}
//入栈操作。如果成功返回,否则
//S:为要操作的栈
//x:为所要入栈的元素
Status push(SeqStack &s,ElemType x)
{
if(s.top==MAXSIZE -1)
return 0;
else
{
s.top++;
s.data[s.top]=x;
return 1;
}
}
//出栈操作。如果成功返回,否则
//S:为所要操作的栈
//x:返回所要出栈的元素
Status pop(SeqStack &s,ElemType &x)
{
if(s.top== 0)
return 0;
else
{
x=s.data[s.top];
s.top--;
return 1;
}
}
//获取栈顶元素操作。如果成功,则返回,否则
//S:为所要操作的栈
//x:返回栈顶元素
Status getTop(SeqStack s,ElemType &x)
{
if(s.top== 0)
return 0;
else
{
x=s.data[s.top];
return 1;
}
}
//遍历栈元素操作,按从栈顶到栈底的顺序遍历的栈中元素
//S:为所要遍历的栈
//visit:遍历过程所用的操作
void display(SeqStack &s)
{
for(int i=s.top;i>0;i--)
printf("%d ",s.data[i]);
printf("\n");
}
//判断栈是否为空,若空,返回真,否则返回假
int stackEmpty(SeqStack s)
{
if(s.top== 0)
return TRUE;
else
return FALSE;
}
int main()
{
SeqStack st;
initStack(st);//初始化
push(st,2);push(st,4);push(st,7);push(st,9);//输入
display(st);//遍历
while(!stackEmpty(st)){
ElemType e;
getTop(st,e);
printf("%d ",e);
pop(st,e);
printf("%d %d\n",e,st.top);
}
return 0;
}