栈的顺序实现和链接实现

栈–后进先出的线性表

顺序实现

#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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值