线性表——顺序栈

#include <bits/stdc++.h>
using namespace std;

#define MaxSize 2
typedef struct{
	int data[MaxSize];
	int top;
}SqStack;

//初始化 
void InitStack(SqStack &S){
	S.top=-1;
}

//判断栈空和已入栈元素个数 
void StackEmpty(SqStack S){
	if(S.top==-1)
		cout<<"Stack Empty!"<<endl;
	else
		cout<<"Stack Length:"<<S.top+1<<endl;
}

//入栈 
void Push(SqStack &S,int x){
	if(S.top==MaxSize-1){
		cout<<"Push Error:Stack Full!"<<endl;
		return;
	}
	S.data[++S.top]=x;
}

//出栈 
void Pop(SqStack &S){
	if(S.top==-1){
		cout<<"Pop Error:Stack Empty!"<<endl;
		return;
	}
	S.top--;
}

//取栈顶元素 
void GetTop(SqStack S,int &x){
	if(S.top==-1){
		cout<<"GetTop Error:Stack Empty!"<<endl;
		return;
	}
	x=S.data[S.top];
	cout<<"Stack Top Element:"<<x<<endl;
}

//从栈底到栈顶顺序打印 
void Print(SqStack S){
	if(S.top==-1){
		cout<<"Print Stack Error:Stack Empty!"<<endl;
		return;
	}
	for(int i=0;i<MaxSize;i++)
		cout<<S.data[i]<<" ";
	cout<<endl;
}

int main(){
	int x;
	SqStack S;
	InitStack(S);
	
	StackEmpty(S);
	Push(S,3);
	StackEmpty(S);
	GetTop(S,x);
	Push(S,5);
	StackEmpty(S);
	GetTop(S,x);
	Print(S);
	
	return 0;
}
posted @ 2024-07-11 09:31  小梦贴贴  阅读(17)  评论(0)    收藏  举报