C++重写单链表实现的队列

链式队列示意图

本程序在VS2017下运行通过

#include<iostream>
#include<string.h>
#include<assert.h>
using namespace std;
typedef int ElemType;		//类型重命名

typedef struct LinkNode	  //链式队列的数据节点
{
	ElemType data;
	struct LinkNode *next;
}LinkNode;

class CLinkQueue
{
public:
	CLinkQueue();		//构造函数
	~CLinkQueue();			//析构函数
	LinkNode *BuyNode()		//购买一个数据节点
	{
		LinkNode *pnode = new LinkNode;
		if (NULL == pnode)		//购买节点失败,终止程序
		{
			exit(1);
		}
		memset(pnode, 0, sizeof(LinkNode));
		return pnode;
	}
	void Clear()	//清空该队列,释放所有数据节点
	{
		LinkNode *p = this->_head.next;		//第一个数据节点
		while (NULL != p)
		{
			delete this->_head.next;	//总是删除队头元素
			this->_head.next = p->next;
			p = p->next;
		}
		this->_rear = NULL;
		this->_cursize = 0;
	}
	int GetCursize()	//获取队列当前元素个数
	{
		return this->_cursize;
	}
	
	bool QueueIsEmpty()	//队列是否为空
	{
		return this->GetCursize() == 0;
	}

	LinkNode *GetFront()	//获得队头节点
	{
		if (this->QueueIsEmpty())	//队列已空,不存在队头节点
		{
			return NULL ;
		}
		return this->_head.next;
	}
	LinkNode *GetBack()	//获得队尾节点
	{
		if (this->QueueIsEmpty())	//队列已空,不存在队尾节点
		{
			return NULL;
		}
		return this->_rear;
	}
	bool Push(ElemType kx)	//元素入队
	{
		LinkNode *pnode = this->BuyNode();
		if (pnode == NULL)		//购买节点失败意味着入队失败
		{
			return false;
		}
		pnode->data = kx;
		if (this->QueueIsEmpty())		//空队列如果发生元素入队,头指针(head.next)也需要进行调整
		{
			this->_head.next = pnode;
			this->_rear = pnode;
		}
		else
		{
			this->_rear->next = pnode;	//新购买的节点链入该队列
			this->_rear = pnode;		//队尾指针指向新购买的节点
		}

		this->_cursize += 1;
		return true;
	}
	bool Pop(ElemType &kx)	//元素出队
	{
		if (this->QueueIsEmpty())		//队列已空,没有元素可以出队
		{
			return false;
		}
		LinkNode *firstElem = this->GetFront();
		kx = firstElem->data;
		if (firstElem->next == NULL)	//队列中只有1个数据节点,元素出队后队列为空,队尾指针需要进行调整
		{
			this->_rear = NULL;
		}
		this->_head.next = firstElem->next;
		delete firstElem;
		this->_cursize -= 1;
		return true;
	}
	void Print()	//打印输出该链式队列
	{
		LinkNode *p = this->GetFront();
		while (p != NULL)
		{
			cout << p->data << "    ";
			p = p->next;
		}
		cout << endl;
	}
private:
	LinkNode _head;		//头节点 有头节点就不需要队头指针,head.next就起到了队头指针的作用
	LinkNode *_rear;		//队尾指针
	int _cursize;	//队列当前元素个数
};

CLinkQueue::CLinkQueue()
{
	this->_head.next = this->_rear = NULL;	
	this->_cursize = 0;
	this->_head.data = 0;	//头节点数据域设为0
}

CLinkQueue::~CLinkQueue()
{
	this->Clear();
}

int main()
{
	ElemType arr[] = { 45,67,56,87,54,67,76,4532,4567};
	int n = sizeof(arr) / sizeof(ElemType);
	CLinkQueue lq;
	for (int i = 0; i < n; ++i)
	{
		lq.Push(arr[i]);		//测试入队函数
	}
	lq.Print();			//测试输出函数
	ElemType kx;
	for (int i = 0; i < n; ++i)
	{
		lq.Pop(kx);		//测试出队函数
		cout << kx << "    ";
	}
	cout << endl;
	return 0;
}

运行结果

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/81285161