数据结构 - 双向队列

周六闲来无事,回顾了一下之前写过的一个双向队列,内容比较简单,且我特意在代码间加了注释。嘻嘻。

初始化:

#include<bits/stdc++.h>
#define maxSize 20
using namespace std;

class dqueue
{
	private:
		int front,rear;
		int size;
		char*data;
	public:
	    dqueue();
		virtual~dqueue();
		void pushFront(char);//从头压入队列 
		void pushRear(char);//从尾部压入队列 
	    char popFront();//从 头出队列 
	    char popRear();//从尾部出队列 
	    char topFront();//得到当前队列头部元素 
	    char topRear();//得到当前队列尾部元素 
			
};

dqueue::dqueue()
{
	size=0;
	front=rear=-1;
	data=new char[maxSize];//new一个堆 
}

dqueue::~dqueue()
{
	delete [] data;
}

函数方法:

void dqueue::pushRear(char c)//从尾部压入一个元素,尾部rear在循环的意义下加一 ,然后压入队列 
{
	if((rear+1)%maxSize==front)cout<<"Full!!!"<<endl;
	rear=(rear+1)%maxSize;
	data[rear]=c;
	cout<<endl;
}

void dqueue::pushFront(char c)//从队列头部压入一个元素,由于头部front本就在元素的前一位,先令入队列,然后front在循环的意义下加一 
{
	if((front+1)%maxSize==rear)cout<<"Full!!!"<<endl;
	data[front]=c;
	front=(front+1)%maxSize; 
	cout<<endl;
}

char dqueue::popRear()//从尾部出队列,先返回当前的元素,然后rear在当前意义下循环加一 
{
	if(rear==front)cout<<"empty!!!"<<endl;
	return data[rear];
	rear=(rear+1)%maxSize;
}

char dqueue::popFront()//同入队列一样,注意逻辑顺序,先在循环的意义加一,得到当前出队列的元素,再返回这个值 
{
	if(rear==front)cout<<"empty!!!"<<endl;
	front=(front+1)%maxSize;
	return data[front];
}

char dqueue::topFront()//与popFront类似 
{
	if(rear==front)cout<<"empty!!!"<<endl;
	int i=(front+1)%maxSize;
	cout<<"当前的元素是:"; 
	return data[i];
	cout<<endl;
}

char dqueue::topRear()// 与popRear类似 
{
	if(rear==front)cout<<"empty!!!"<<endl;
	cout<<"当前的元素是:";
	return data[rear];
	cout<<endl;
}

主函数:

//主函数写了一个判断一组简单回文数,功能比较欠缺。。。 
int main()
{
	dqueue p;
	int n,i,j;
	char tem,c;
	char a,b;
	while(1)
	{
		cout<<"请输入添加元素的个数:";
		cin>>n;
		cout<<endl;
		for(i=0;i<n;i++)
		{
			cout<<"请输入一个字符:";
			cin>>c;
			p.pushRear(c);
		}
		j=n/2;
		for(i=0;i<j;i++)
		{
			a=p.popFront();     b=p.popFront();
			if(a==b)continue;
			else cout<<"这组字符不是回文数"<<endl;;
		}
		system("pause");
   }
}

本人使用的是dev c++,所以用了万能头文件<bits/stdc++>,不是所有的编译器都可以用,且这样做代码的效率会变得十分低下,能不用最好不用,我。。。比较懒哈哈哈哈哈

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值