简单链队列C++

#include <iostream>
using namespace std;

template <typename T>
class MyQueue
{
public:
	struct QNode
	{
		T data;
		QNode *next;
		QNode()
		{
			next=NULL;
		}
	};
	
	MyQueue()
	{
		initQueue();
	}
	~MyQueue()
	{

	}
	void initQueue()
	{
		length=0;
		front=NULL;
		rear=NULL;
	}
	bool clearQueue()
	{
		if (isEmpty())
		{
			return true;
		}
		else
		{
			while(front!=rear)
			{
				deQueue();
			}
		}
	}
	bool isEmpty()
	{
		if (rear==NULL&&front==NULL)
		{
			return true;
		}
		return false;
	}
	T getHead()
	{
		return front->next->data;
	}
	bool enQueue(T e)
	{
		QNode *Node;
		Node=new QNode;
		Node->data=e;
		if (front==NULL&&rear==NULL)
		{
			front=new QNode;
			rear=new QNode;
			front->next=Node;
			rear=Node;
		}
		else{
		rear->next=Node;
		rear=Node;
		}
		length++;
		return true;
	}
	T deQueue()
	{
		if (isEmpty())
		{
			return 0;
		}
		T e;
		QNode *p=new QNode;
		if (front->next==rear)
		{
			p=rear;
			front=NULL;
			rear=NULL;
			e=p->data;
			free(p);

		}
		else
		{
			p=front->next;
			front->next=front->next->next;
			e=p->data;
			free(p);
		}
		length--;
		
		return e;
	}
	bool deQueue(QNode *e)
	{
		if (isEmpty())
		{
			return false;
		}
		QNode *p=new QNode;
		if (front->next==rear)
		{
			p=rear;
			front=NULL;
			rear=NULL;
			e=p;
			free(p);
			
		}
		else
		{
			p=front->next;
			front->next=front->next->next;
			e=p;
			free(p);
		}
		length--;
		return true;
	}
	int getLength()
	{
		return length;
	}
	void displayQueue()
	{
		if (isEmpty())
		{
			cout<<"Empty Queue"<<endl;
			return;
		}
		QNode *p=front->next;
		while(p->next!=NULL)
		{
			cout<<p->data<<"   ";
			p=p->next;
		}
		cout<<rear->data;
		cout<<endl;
	}
	private:
		QNode *front;
		QNode *rear;
		int length;
};
int main()
{
	MyQueue<int> queue;
	for (int i=0;i<10;i++)
	{
		queue.enQueue(i+1);
	}
	queue.displayQueue();
	
	queue.deQueue();
	queue.displayQueue();
	cout<<queue.getHead()<<endl;
	queue.clearQueue();
	queue.displayQueue();
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值