受限的线性表~栈~顺序栈

#include<iostream>
#define MaxSize 50 
typedef int DataType;
using namespace std;

//栈的数据结构 
//顺序栈
/*
	数据运算:
	1.初始化一个空栈:初始指针==-1
	2.数据元素入栈:如果栈没满,数据元素入栈
	3.数据元素出栈:如果栈没空,数据元素出栈
	4.得到栈顶元素:如果栈没空,取栈顶元素
	5.销毁顺序栈 

	判断条件
	1.栈空 s.top==-1
	2.栈满 s.top=MaxSize-1
	3.入栈语句:s.top先加,数据元素在入栈  s.data[++s.top]=x
	4.出栈语句:数据元素先出栈,s.top后--  x=s.data[s.top--]
*/

typedef struct node{
	DataType data[MaxSize];  //存放栈中的数据 
	int top;  //存放栈顶指针 
}SqStack;

//初始一个空栈
void InitStack(SqStack &S){
	S.top=-1;   //初始时,栈顶指针指向-1 
} 
//判断栈是否为空
bool StackEmpty(SqStack &S){
	if(S.top==-1)
		return true;   //栈空 
	else{
		return false;  //不空 
	}
		
}
//入栈,要判断栈是不是满了 
bool Push(SqStack &S,DataType x){
	if(S.top==MaxSize-1){
		cout<<"栈满了!无法入栈"<<endl;
		return false; 
	} 
	S.data[++S.top]=x;
	return true; 
} 
//出栈,判断是不是在栈空
bool Pop(SqStack &S,DataType &x){
	if(S.top==-1){
		cout<<"顺序栈为空!,无法出栈"<<endl;
		return false;
	}
	x=S.data[S.top--];
	return true;
} 
//读出栈顶元素
bool GetTop(SqStack &S,DataType &x){
	if(S.top==-1){
		cout<<"顺序栈为空!无法读出"<<endl;
		return false;
	}
	x=S.data[S.top];
	return true;
}
//销毁顺序栈
void DestoryStack(SqStack &S){
	S.top==-1;
} 
int main(){
	SqStack S;
	InitStack(S);
	int x;
	Push(S,12);
	Pop(S,x);
	cout<<x<<endl;
	Pop(S,x);
	DestoryStack(S);
	return 0;
} 
 

  

posted @ 2021-02-14 15:53  nanfengnan  阅读(18)  评论(0编辑  收藏  举报