链队列的C++实现

链队列从本质上来看就是操作受限的单链表,其中表尾代表队头,首元结点代表队尾(方便插入操作)。

头文件:LinkQueue.hpp

#pragma once
#include<iostream>
using namespace std;

template<class T>
class Node
{
public:
	Node() {}
	Node(T d) { data = d; }
	T data;
	Node<T>* next;
};

template<class T>
class LinkQueue
{
public:
	LinkQueue();		//构造函数
	void EnQueue(T d);	//入队
	T DeQueue();		//出队
	T get_front();		//获取队头元素
	bool is_empty();	//判断队列是否为空
	~LinkQueue();		//析构函数
private:
	Node<T>* front, * rear;
};

template<class T>
LinkQueue<T>::LinkQueue()
{
	this->front = new Node<T>;
	rear = front;
}//构造函数

template<class T>
void LinkQueue<T>::EnQueue(T d)
{
	Node<T>* p = new Node<T>(d);
	rear->next = p;
	rear = p;
}//入队

template<class T>
T LinkQueue<T>::DeQueue()
{
	if (rear == front)
		throw "underflow error";
	Node<T>* p = front->next;
	T d = p->data;
	front->next = p->next;
	delete p;
	if (front->next == NULL)
		rear = front;
	return d;
}//出队

template<class T>
T LinkQueue<T>::get_front()
{
	if (front == rear)
		throw "underflow error";
	return front->next->data;
}//获取队头元素

template<class T>
bool LinkQueue<T>::is_empty()
{
	return front == rear ? true : false;
}//判断队列是否为空

template<class T>
LinkQueue<T>::~LinkQueue()
{
	while (front)
	{
		rear = front;
		front = front->next;
		delete rear;
	}
}//析构函数

编写主函数测试:sketch.cpp

#include"LinkQueue.hpp"


int main()
{
	LinkQueue<int> q;
	for (int i = 1; i < 6; i++)
	{
		q.EnQueue(i);
	}

	while (!q.is_empty())
		cout << q.DeQueue() << endl;

	//DeQueue异常处理机制测试
	try
	{
		q.DeQueue();
	}
	catch (const char* err)
	{
		cout << err << endl;
	}

	//get_front异常处理机制测试
	try
	{
		q.get_front();
	}
	catch (const char* err)
	{
		cout << err << endl;
	}
	
	

	return 0;
}

运行结果:

 


每天都要加油哦 ^_^

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值