c++实现队列

队列的数据结构中一种特殊的线性表,特点是“先入先出,后入后出”,如下图:

按照队列的特点我们可以自己实现队列,程序如下:

//Queue.hpp

#pragma once
#include<iostream>
#include<assert.h>
#include<string>
using namespace std;

template<class T>
struct Node
{
	Node(const T& d)
	:_data(d)
	,_next(NULL)
	{}
	T _data;
	Node<T>* _next;
};
template<class T>
class Queue
{
public:
	Queue()
		:_head(NULL)
		,_tail(NULL)
		, _size(0)
	{}
	~Queue()
	{
		while (!Empty())
		{
			Pop();
		}
	}
	Queue(const Queue<T>& q) 
		:_head(NULL)
		,_tail(NULL)
		, _size(0)
	{
		Node<T>* cur = q._head;
		while (cur)
		{
			Push(cur->_data);
			cur = cur->_next;
		}
	}
	Queue<T>& operator=(Queue<T> q)
	{
		swap(_head, q._head);
		swap(_tail, q._tail);
		_size = q._size;
		return *this;
	}
	void Push(const T& d)
	{
		Node<T>* NewNode = new Node<T>(d);
		if (_head == NULL)
		{
			_head = NewNode;
			_tail = NewNode;
		}
		else
		{
			_tail->_next = NewNode;
			_tail = NewNode;
		}
		_size++;
	}
	void Pop()
	{
		if (_head == NULL)
			return;
		if (_head == _tail)
		{
			delete _head;
			_head = NULL;
			_tail = NULL;
		}
		else
		{
			Node<T>* del = _head;
			_head = _head->_next;
			delete del;
		}
		_size--;
	}
	T& Front() const
	{
		assert(_head);
		return _head->_data;
	}
	T& Back() const
	{
		assert(_tail);
			return _tail->_data;
	}
	bool Empty() const
	{
		return _head == NULL;
	}
	size_t Size() const
	{
		return _size;
	}
protected:
	Node<T>* _head;
	Node<T>* _tail;
	size_t _size;
};

//test.cpp

#include "Queue.hpp"
#include<string>
void test()
{
	Queue<string> q1;
	q1.Push("111111111111");
	q1.Push("222222222222");
	q1.Push("333333333333");
	q1.Push("444444444444");
	q1.Push("555555555555");
	Queue<string> q2(q1);
	Queue<string> q3;
	q3=q1;
	cout << q3.Size() << endl;
	while (!q3.Empty())
	{
		cout <<q3.Front()<< endl;
		q3.Pop();
	}

}

int main()
{
	test();
	getchar();
	return 0;
}

运行结果:









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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值