顺序栈——C++实现

#include<iostream>
#include<malloc.h>
#define MAXSIZE	50
using namespace std;

typedef int DataType;
typedef struct{
	DataType data[MAXSIZE];
	int top;
}SeqStack,* PSeqStack;

int main(){
	//函数声明
	PSeqStack Init_SeqStack(void);				/*建空栈*/
	void Push_SeqStack(PSeqStack S,DataType x);	/*入栈*/
	void Creat_SeqStack(PSeqStack S);			/*建非空栈*/
	int Empty_SeqStack(PSeqStack S);			/*判断栈是否为空*/
	void Pop_SeqStack(PSeqStack S,DataType * y);/*出栈*/		
	int GetTop_SeqStack(PSeqStack S);			/*取栈顶元素*/
	void Show_SeqStack(PSeqStack S);			/*输出栈*/
	void Destroy_SeqStack(PSeqStack * S);		/*销毁栈*/

	PSeqStack S=Init_SeqStack();
	cout<<"创建一个顺序栈,请输入栈元素(最多"<<MAXSIZE<<"个),以负数结束:";
	Creat_SeqStack(S);
	Show_SeqStack(S);

	int x;
	cout<<"\n\n请输入要入栈的元素值:";
	cin>>x;
	Push_SeqStack(S,x);
	Show_SeqStack(S);

	int y;
	Pop_SeqStack(S,&y);
	cout<<"\n\n删除的栈顶元素值为:"<<y<<endl;
	Show_SeqStack(S);

	cout<<"\n\n栈顶元素值为:"<<GetTop_SeqStack(S);
	
	Destroy_SeqStack(&S);
	return 0;
}


/*建空栈*/
PSeqStack Init_SeqStack(void){
	PSeqStack S;
	S=(PSeqStack)malloc(sizeof(SeqStack));
	if(S){
		S->top = -1;//表示空栈
	}
	return S;
}

/*入栈*/
void Push_SeqStack(PSeqStack S,DataType x){
	if(S->top == MAXSIZE-1){
		cout<<"栈满不能入栈!";
	}else{
		S->top++;
		S->data[S->top]=x;	
	}
}

/*建非空栈*/
void Creat_SeqStack(PSeqStack S){
	DataType x;
	while(true){
		cin>>x;
		if(x >= 0)
			Push_SeqStack(S,x);
		else
			break;
	}
}

/*判断栈是否为空*/
int Empty_SeqStack(PSeqStack S){
	if(S->top == -1)
		return 1;
	else
		return 0;
}

/*出栈*/
void Pop_SeqStack(PSeqStack S,DataType * y){
	if(Empty_SeqStack(S)){
		cout<<"栈空不能出栈!";
	}else{
		* y=S->data[S->top];
		S->top--;	
	}
}

/*取栈顶元素*/
int GetTop_SeqStack(PSeqStack S){
	if(Empty_SeqStack(S)){
		cout<<"栈空!";
		return -1;
	}
	return S->data[S->top];
}

/*输出栈*/
void Show_SeqStack(PSeqStack S){
	cout<<"输出顺序栈为:";
	int p=S->top;
	while(p>= 0){
		cout<<S->data[p]<<" ";
		p--;
	}
}

/*销毁栈*/
void Destroy_SeqStack(PSeqStack * S){
	if(* S)
		free(* S);

	* S=NULL;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值