简单链队列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;
}

原文链接: https://www.cnblogs.com/Vulkan/archive/2012/10/17/7530245.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    简单链队列C++

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/66085

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午12:09
下一篇 2023年2月9日 下午12:09

相关推荐