【无标题】

数据结构之栈
栈又名堆栈,是一种线性表结构,受限制与只能再尾部进行插入和删除操作,所以它是先进后出的一个算法,生活中有很多案例都是用到了栈这样一个结构。
下面是关于顺序栈的简单操作

#include<iostream>
using namespace std;
#define MaxSize 50
typedef char ElemType; 
typedef struct SqStack{
	ElemType data[MaxSize];
	int top;	
}SqStack;
//栈空条件是S.top=-1,而栈满的条件是S.top==MaxSize-1,栈长等于S.top+1; 
 //初始化栈 
 void InitStack(SqStack &s){
 	s.top=-1;//初始化栈顶指针 
 } 
 //判定栈是否空 
 bool IsEmpty(SqStack s){
 	if(s.top==-1)
 		return true;//空 
 	else 
 		return false;//非空 
 }
 //数据进栈
 bool Push(SqStack &s,ElemType e){//加上引用符号,因为数据是要能够返回原来的地址的 
 	if(s.top==MaxSize-1){
 			return false;//说明栈满,不能在添加数据了,报错 
	 } 
	 s.data[++s.top]=e;//因为栈顶指针一开始是-1,要让他先加1在进行赋值 
	 return true;
 } 
 //数据出栈
 bool Pop(SqStack &s,ElemType &e){//要将弹出的元素值输出,所以要用引用类型保存数据
 	if(s.top==-1){
 			return false;//栈空 
	 } 
	 e=s.data[s.top--];//因为是取数,取完栈内元素减1,栈顶指针就要减1.
	 //e=s.data[s.top];
	 //s.top=s.top-1; 两者等价 
 } 
 //读书栈顶元素
 bool getTop(SqStack s,ElemType &e){
 	if(s.top==-1){
 		return false;
	 }
	 e=s.data[s.top];
	 return true;
 } 
 bool PushOut(SqStack &s){
 	if(s.top==-1){
 		return false;
	 }
	while(s.top!=-1){
		cout<<s.data[s.top--]<<" ";
	}
	cout<<endl;
 }
 int main(){
 	SqStack s;
 	InitStack(s);
 	int n;
 	char a=97;
	ElemType e;
 	cin>>n;
 	cout<<"入栈:"; 
 	while(n>0){
 		Push(s,a);
 		cout<<a<<" "; 
 		a++;
 		n--;
	 }
	Pop(s,e); 
	cout<<"弹出栈顶元素:"<<e<<endl; 
	getTop(s,e);
	cout<<"栈顶元素:" ;
	cout<<e<<endl;
	cout<<"出栈:" ;
	PushOut(s);
 	return 0;
 } 

同时还有链栈

#include<iostream>
using namespace std;
typedef int ElemType;

typedef struct Linknode{
	ElemType data;
	struct Linknode *next;
}Linknode,*stack;
//初始化链栈
void init(stack &s){
	s=NULL;//将栈顶指针置空 
} 
bool push(stack &s,ElemType e){
	//创建新结点,并且移动 
	stack node=new Linknode();
	node->next=s;
	node->data=e;
	s=node;
return true; 
bool pop(stack &s,ElemType &e){
} 
	stack p;
	if(s->next==NULL){
		return false;//说明栈内没有数据,若有一定不为空 
	}
	e=s->data;
	p=s;
	s=s->next;//栈顶结点向后移 
	delete p;//删除无效的结点 
return true;
}
void output(stack s){
	while(s!=NULL){
		cout<<s->data<<" ";
		s=s->next; 
	} 
	cout<<endl;
}
int main(){
	stack s;
	init(s);
	int i;
	cin>>i;
	while(i>0){
		push(s,i);
		cout<<i<<" ";
		i--;
	}
	cout<<endl;
	output(s);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值