顺序栈的实现

栈关键点:后进先出,先进后出;

借助数组和"指针"来实现:

<span style="font-size:18px;">#include<iostream>
using namespace std;
const  int smax=30;
template <class Datatype>
class Secsteck
{
	public:
		Secsteck(){top=-1;}
		~Secsteck(){}
		void Set(Datatype a[],int n);//先建立一个基础栈,为后续操作做准备
		void Push(Datatype x);//入栈
		Datatype Pop();//出栈
		Datatype Get(){if(top!=-1)return data[top];}//取出栈顶元素
		int Empty(){return top==-1 ? 1:0;}//判断栈是否为空?
        
    private:
		int top;
		Datatype data[smax];
		
};
template <class Datatype>
void Secsteck<Datatype>::Set(Datatype a[],int n)//先建立3个元素,建立一个基础栈
{
	if (top==smax-1)throw;//"上溢"
    {for (int i=0;i<n;i++)
		data[++top]=a[i];
	}
	cout<<"基础栈建好"<<endl;
}
template <class Datatype>
void Secsteck<Datatype>::Push(Datatype x)             //入栈
{
  if (top==smax-1)throw;//"上溢"
      data[++top]=x;
      cout<<x<<"入栈成功"<<endl;
}
template <class Datatype>    //出栈
Datatype Secsteck<Datatype>::Pop()
{
  if (top==-1)throw;//"下溢"
	  return data[top--];
}
int main()
{
	int n=3;int s[smax];
	cout<<"请输入三个数:";
		for(int i=0;i<n;i++)
		cin>>s[i];
	Secsteck<int> a;
	a.Set(s,n);
	cout<<"请输入一个数准备入栈:";
	int m;
	cin>>m;
	a.Push(m);
	cout<<"出栈结果: "<<a.Pop()<<endl;
	cout<<"取出栈顶元素:  "<<a.Get()<<endl;
	cout<<"判段栈顶是否为空,1为空,0为非空:  "<<a.Empty();
	return 0;
}</span>
调试结果:


总结:

主要是做好对"指针"top的利用.若要逆序实现,也是对top进行相应的改变.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值