栈的定义
栈是只允许一一端进行操作的的线性表,首先强调的是栈是一种线性表,其次栈只限定在一端进行操作。
基本操作
initstack() 初始化栈
stackempty() 判断栈空
push() 进栈
pop() 出栈
gettop() 获取栈顶元素
destorystack() 销毁栈
顺序栈的实现
初始化
typedef struct{
int data[MAX];
int top;
}sqstack;
//初始化
void initStack(sqstack &S){
S.top=-1;
}
栈空
bool isNull(sqstack &S){ //或者stackEmpty()
if(S.top == -1){
return true;
}
else{
return false;
}
}
进出栈
//进
bool push(sqstack &S,int x){
if(S.top == MAX-1){
return false;
}
S.data[++S.top] = x;
return true;
}
//出
bool pop(sqstack &S , int &x){
if(S.top == -1){
return false;
}
x = S.data[S.top--];
return true;
}
读顶部元素
//读顶
int GetTop(sqstack &S){
if(S.top == -1){
return false;
}
int ele = S.data[S.top];
return ele;
}
测试整合代码
#include <iostream>
#define MAX 100
using namespace std;
typedef struct{
int data[MAX];
int top;
}sqstack;
//初始化
void initStack(sqstack &S){
S.top=-1;
}
//判栈空
bool isNull(sqstack &S){ //或者stackEmpty()
if(S.top == -1){
return true;
}
else{
return false;
}
}
//进
bool push(sqstack &S,int x){
if(S.top == MAX-1){
return false;
}
S.data[++S.top] = x;
return true;
}
//出
bool pop(sqstack &S , int &x){
if(S.top == -1){
return false;
}
x = S.data[S.top--];
return true;
}
//读顶
int GetTop(sqstack &S){
if(S.top == -1){
return false;
}
int ele = S.data[S.top];
return ele;
}
int main (){
sqstack Sta;
initStack(Sta);
if(isNull(Sta)){
cout<<"栈空"<<endl;
}
push(Sta,23);
GetTop(Sta);
int record = 0;
pop(Sta,record);
cout << record<<endl;
if(isNull(Sta)){
cout<<"栈空"<<endl;
}
return 0;
}