栈的特点为(后进先出)。
初步定义
顺序栈的存储结构包括1.地址(数组名)2.站定下标
代码:
typedef struct
{
int top;
ElemType *elem;
} sqstack;
一.初始化
1.创建数组并定义指针指向首地址。
2.判断是否创建成功。
3.让下标初始化为-1。
代码:
status Initstack(sqstack &S)
{
S.elem=new ElemType[MAXSIZE];
if(!S.elem) return ERROR;
S.top=-1;
return OK;
}
二.入栈
1.判断是否栈满(s.top==MAXSIZE-1)。
2.将s.top+1(指向准备存入的数组下标)。
3.将e赋值给s.elem[s.top]。
代码:
status push(sqstack &S,ElemType &e)
{
if(S.top==MAXSIZE-1) return ERROR;
S.top++;
S.elem[S.top]=e;
return OK;
}
三.出栈
1.判断是否栈空(s.top==-1)。
2.将s.elem[s.top]付给e。
3.删除栈顶元素(即令栈顶下标向下移动一格)。
代码:
status Pop(sqstack &S,ElemType &e)
{
if(S.top==-1) return ERROR;
e=S.elem[S.top];
S.top--;
return OK;
}
四.取栈顶元素
1.判断是否栈空.
2.取值
代码:
ElemType GetTop(sqstack S,ElemType &e)
{
if(S.top==-1) return ERROR;
e=S.elem[S.top];
return OK;
}
五.展示
1.判断是否栈空。
2.用for循环,逐一输出栈中元素.
代码:
status show(sqstack S)
{
int i;
if(S.top==-1)
cout<<"栈空";
for(i=0;i<S.top;i++)
{
cout<<S.elem[i]<<" ";
}
cout<<endl;
}
总代码(都需采用菜单函数的形式)
代码:
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef int status;
typedef struct
{
int top;
ElemType *elem;
} sqstack;
status Initstack(sqstack &S);
status push(sqstack &S,ElemType &e);
status Pop(sqstack &S,ElemType &e);
ElemType GetTop(sqstack S,ElemType &e);
status show(sqstack S);
int main()
{
sqstack S;
int choice;
while(1)
{
cout<<"1.初始化 2.入栈 3.出栈 4.取栈顶元素 5.展示"<<endl;
cout<<"Input choice:";
cin>>choice;
switch(choice)
{
case 1:
if(Initstack(S)==ERROR) cout<<"初始化失败"<<endl;
else cout<<"初始化成功"<<endl;
break;
case 2:
{
ElemType e;
cout<<"插入数据:";
cin>>e;
if(push(S,e)==OK) cout<<"入栈成功"<<endl;
else cout<<"入栈失败"<<endl;
break;
}
case 3:
ElemType e;
if(Pop(S,e)==ERROR)
cout<<"出栈失败"<<endl;
else cout<<"出栈成功"<<endl;
break;
case 4:
if(GetTop(S,e)==ERROR)
cout<<"取值失败"<<endl;
else
cout<<"栈顶元素为"<<e<<endl;
break;
case 5:
if(show(S)==OK)
cout<<"读取成功"<<endl;
break;
}
system("pause");
system("cls");
}
}
status Initstack(sqstack &S)
{
S.elem=new ElemType[MAXSIZE];
if(!S.elem) return ERROR;
S.top=-1;
return OK;
}
status push(sqstack &S,ElemType &e)
{
if(S.top==MAXSIZE-1) return ERROR;
S.top++;
S.elem[S.top]=e;
return OK;
}
status Pop(sqstack &S,ElemType &e)
{
if(S.top==-1) return ERROR;
e=S.elem[S.top];
S.top--;
return OK;
}
ElemType GetTop(sqstack S,ElemType &e)
{
if(S.top==-1) return ERROR;
e=S.elem[S.top];
return OK;
}
status show(sqstack S)
{
int i;
if(S.top==-1)
cout<<"栈空";
for(i=0;i<S.top;i++)
{
cout<<S.elem[i]<<" ";
}
cout<<endl;
}