栈–后进先出的线性表
顺序实现
#include <iostream>
using namespace std;
typedef char datatype;
const int maxsize=100;
typedef struct{
datatype data[maxsize];
int top;
}sqstack;
void init_sqstack(sqstack *sq){
sq->top=-1;
cout<<"初始化成功"<<endl;
}
int empty_sqstack(sqstack *sq){
if(sq->top==-1) return 1;
else return 0;
}
int push_sqstack(sqstack *sq,datatype x){
if(sq->top==maxsize-1){
cout<<"栈满,不能进栈!\n";
return 0;
}
sq->data[++sq->top]=x;
return 1;
}
int pop_sqstack(sqstack *sq,datatype *x){
if(sq->top==-1){
cout<<"栈空,不能退栈!\n";
return 0;
}
*x=sq->data[sq->top--];
return 1;
}
int gettop_sqstack(sqstack *sq,datatype *x){
if(sq->top==-1){
cout<<"栈空,无栈顶可取!\n";
return 0;
}
*x=sq->data[sq->top];
return 1;
}
int main(){
sqstack sq;
int x;
int i;
char k = 's';
do{
cout<<"0、退出"<<endl;
cout<<"1、初始化"<<endl;
cout<<"2、判栈空"<<endl;
cout<<"3、入栈"<<endl;
cout<<"4、出栈"<<endl;
cout<<"5、取栈顶"<<endl;
cin>>x;
switch(x){
case 0: return 0;
case 1: init_sqstack(&sq);break;
case 2: i = empty_sqstack(&sq);
if(i){
cout<<"栈空"<<endl;
}else cout<<"栈不为空"<<endl;
break;
case 3: push_sqstack(&sq,'q');break;
case 4: pop_sqstack(&sq,&k);break;
case 5: i = gettop_sqstack(&sq,&k);
if(i){
cout<<"栈顶元素:"<<k<<endl;
}
break;
}
}while(x!=0);
return 0;
}
链接实现
#include <iostream>
using namespace std;
typedef char datatype;
typedef struct node * pointer;
struct node{
datatype data;
pointer next;
};
typedef struct{
pointer top;
}lkstack;
void init_lkstack(lkstack *ls){
ls->top=NULL;
}
int empty_lkstack(lkstack *ls){
if(ls->top==NULL) return 1;
else return 0;
}
void push_lkstack(lkstack *ls,datatype x){
pointer p;
p = new node;
p->data = x;
p->next = ls->top;
ls->top = p;
}
int pop_lkstack(lkstack *ls,datatype *x){
pointer p;
if(ls->top==NULL){
cout<<"栈空,不能退栈!\n"<<endl;return 0;
}
p=ls->top;
*x = p->data;
ls->top = p->next;
delete p;
return 1;
}
int gettop_lkstack(lkstack *ls,datatype *x){
if(ls->top==NULL){
cout<<"栈空,无栈顶可取!\n";return 0;
}
*x = ls->top->data;
return 1;
}
int main(){
lkstack ls;
int x;
int i;
char k = 's';
do{
cout<<"0、退出"<<endl;
cout<<"1、初始化"<<endl;
cout<<"2、判栈空"<<endl;
cout<<"3、入栈"<<endl;
cout<<"4、出栈"<<endl;
cout<<"5、取栈顶"<<endl;
cin>>x;
switch(x){
case 0: return 0;
case 1: init_lkstack(&ls);break;
case 2: i = empty_lkstack(&ls);
if(i){
cout<<"栈空"<<endl;
}else cout<<"栈不为空"<<endl;
break;
case 3: push_lkstack(&ls,'q');break;
case 4: pop_lkstack(&ls,&k);break;
case 5: i = gettop_lkstack(&ls,&k);
if(i){
cout<<"栈顶元素:"<<k<<endl;
}
break;
}
}while(x!=0);
return 0;
}