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;
}

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

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


版权声明:本文为m0_67500944原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。