c++ 队列实现

/*
队列的链表实现
*/

#include<iostream>
using namespace std;

template<class T>
struct Node
{
	Node<T> *next;
	T data;

	Node()
	{
		next=NULL;
	}

	Node(T element)
	{
		this->data=element;
		next=NULL;
	}
};

template<class T>
class Queue
{
public:
	//生成队列
	Queue();

	//队尾入队
	void Enqueue(T data);

	//队头出队并
	void Dequeue();

	//获取队头元素
	T front_element();

	bool isEmpty();

	void clear();

	size_t getSize();

private:
	Node<T> *front,*rear;
	size_t size;
};

template<class T>
Queue<T>::Queue()
{
	front=rear=NULL;
	size=0;
}

template<class T>
void Queue<T>::Enqueue(T data)
{
	if(rear==NULL)
	{
		front=rear=new Node<T>(data);
	}
	else
	{
		rear->next=new Node<T>(data);
		rear=rear->next;
	}

	size++;
}

template<class T>
void Queue<T>::Dequeue()
{
	if(size==0)
	{
		cout<<"No element in the queue";
	}
	else
	{
		Node<T> *temp=front;
		front=front->next;
		if(front==NULL)
		{
			rear=NULL;
		}
		size--;
		delete temp;
	}
}

template<class T>
T Queue<T>::front_element()
{
	if(size==0)
	{
		cout<<"No elements in the queue";
		return -1;
	}
	else
	{
		return front->data;
	}
}

template<class T>
void Queue<T>::clear()
{
	while(front!=NULL)
	{
		Node<T> *temp=front;
		front=front->next;
		delete temp;
		size--;
	}
	rear=NULL;
}

template<class T>
bool Queue<T>::isEmpty()
{
	return front==NULL;
}

template<class T>
size_t Queue<T>::getSize()
{
	return size;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值