C++实现队列

队列的定义
队列值允许在表的队尾进行插入,在表对头进行删除。队列具有先进先出的特性。(FIFO,first In First Out)


#define _CRT_SECURE_NO_WARNINGS 1


//队列先进先出
#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;
};


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();
system("pause");
return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值