C++代码实现栈基本操作

其实我们都了解栈的定义,会感觉很简单。但是需要动手打一下代码才知道实现的方式。

简单说一下定义:

        栈是限定仅在表的一端进行插人和删除操作的线性表,允许 插人和删除的一端称为栈顶(stack top),另一端称为栈底(stack bottom),不含任何数据元素的栈称为空栈。

        任何时刻出栈的元素都只 能是栈顶元素,即最后入栈者最先出栈,所以栈中元素除了具有线性关系外,还具有后进 人栈。

下面说一下顺序栈的代码:

实现的功能:

  • 初始化InitStack
  • 判空Empty
  • 进栈Push
  • 出栈Pop
  • 读栈顶元素GetTop
  • 遍历栈PrintStack
  • 销毁栈DestroyStack
#include<iostream>
using namespace std;
const int StackSize=10;
class SepStack
{
	public:
		SepStack(){//初始化,InitStack 
			top=-1;
		};
		~SepStack(){//销毁栈,DestroyStack 
			top=-1;
			cout<<"end";
		};
		void Push(int x){//入栈 
			if(top==StackSize-1){
				cout<<"栈满";
				return; 
			};
			 data[++top]=x;
		};
		int Pop(){//出栈 
			int x;
			if(top==-1){
				cout<<"栈空"<<endl;
				return 0; 
			};
			x=data[top--];
			 return x;
		};
		int GetTop(){//读取 
			int x;
			if(top==-1){
				cout<<"栈空"<<endl;
				return 0; 
			};
			x=data[top];
			 return x;
		};
		bool Empty(){//判断 
			if(top==-1)
			return false;
			else
			return true;
		};
		void PrintStack(){
			while(top!=-1){
				cout<<data<<" ";
			}
			cout<<endl;
		} 
		
	private:
		int data[StackSize];
		int top;
		
};

 接下来是主函数部分,写几个题看看效果。

需要完成

 主函数如下:

int main(){
	int x,y;//数量 
	int n;//入栈数字 
	SepStack s;
	cin>>x;
	y=x;
	for(int i=0;i<x;i++){
		cin>>n;
		s.Push(n);
		if(n==y){
			y--;
			cout<<s.Pop()<<" ";
	//		cout<<" "; 
		}
	}
	s.PrintStack();
	return 0;
}

可以看出,使用上面创建的类即可,以上是我的代码,如有更好的,请发在留言区一起讨论。

希望可以得到大家点赞鼓励!!

  • 22
    点赞
  • 89
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值