利用数组实现双端栈

#include <iostream>
using namespace std;
const int size=50;
typedef int StackElement;


class DoubleStack
{
private:
	StackElement array[size];
	int frontTop;
	int backTop;
public:
	DoubleStack()
	{
		frontTop=-1;
		backTop=size;
	}
    
	bool empty() const;
	bool full() const;
	void frontPush(StackElement item);//前端入栈
	void backPush(StackElement item);//后端入栈
    void frontPop();                 //前端出栈
    void backPop();                  //后端出栈
	void display();
	
};


 bool DoubleStack ::empty() const
	{
		if(frontTop==-1&&backTop==size)
		{
		   cout<<"栈已满"<<endl;
			return true;
		}
		else 
		{
		
			return false;
		}
	}

 	bool DoubleStack :: full() const
	{
		if(frontTop>=backTop-1)
		{
		 cout<<"栈全空"<<endl;
			return true;
		}
		else 
		{
		
			return false;
		}
	}

		void DoubleStack ::frontPush(StackElement item)
	{
		frontTop+=1;
		if(!full())
		{	
			array[frontTop]=item;
		
		}
	}
	
	void DoubleStack ::backPush(StackElement item)
	{
		backTop-=1;
		if(!full())
		{	
			array[backTop]=item;
		}
	}
	

	
	void  DoubleStack ::frontPop()
	{
		if(!empty())
		{
			frontTop-=1;
		cout<<"前端栈出栈成功!"<<endl;
		}
	}
	
	void  DoubleStack ::backPop()
	{
		if(!empty())
		{
			backTop+=1;
			cout<<"后端栈出栈成功!"<<endl;
		}
	}
	void DoubleStack ::display()
	{
	    cout<<"前端栈:";
		int i=0,j=0;
		while(i<=frontTop)
		{
			if(j%5==0)
			cout<<endl;
			cout<<array[i]<<" ";
			j++;
			i++;	
		}
        cout<<endl;
	
		i=size-1;
		j=0;
	   cout<<"后端栈:";
		while(i>=backTop)
		{
			if(j%5==0)
				cout<<endl;
		  cout<<array[i]<<" ";	
			j++;
			i--;	
		}
	 		cout<<endl;
	}


void main(void)
{
	//初始化双端栈
     DoubleStack *s;
	s=new DoubleStack;
	int temp;
	int t=-1;
   cout<<"选项: 1-前端入栈 2-后端入栈 3-前端出栈 4-后端出栈 5-双端栈显示"<<endl;
	while(1)
	{
		cout<<"输入选项:";
		cin>>t;
		if(t==1)
		{
		cout<<"输入入栈元素:";	
			cin>>temp;
			s->frontPush(temp);
		}
		else if(t==2)
		{
			cout<<"输入入栈元素:";
			cin>>temp;
			s->backPush(temp);
		}
		else if(t==3)
		{
			s->frontPop();
		}
		else if(t==4)
		{
			s->backPop();
		}
		else if(t==5)
		{
			s->display();
		}
		else 
			cout<<"请重新输入:"<<endl;
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值