您的位置:首页 > 理论基础 > 数据结构算法

2016-04-11 23:00 267 查看

队即是仅允许在尾部进入,在头部出的顺序表,即“先进先出”
#include<iostream>
#include<assert.h>
using namespace std;

template<class T>
struct Node
{
T _data;
Node<T>*_next;
Node(const T &x)
:_data(x)
, _next(NULL)
{
}
};
template<class T>
class Queue
{
public:
Queue()
:_head(NULL)
, _tail(NULL)
{}

Queue(const Queue<T>&q)
:_head(NULL)
, _tail(NULL)
{
Node<T>*cur = q._head;
while (cur)
{
Push(cur->_data);
cur = cur->_next;
}
}

Queue& operator=( Queue<T>&q)
{
swap(_head, q._head);
swap(_tail, q._tail);
return *this;
}

~Queue()
{
if (_head == NULL)
return;
Node<T>*cur = _head;
while (cur->_next!=NULL)
{
Node<T>*del=cur;
cur = cur->_next;
delete del;
}
delete cur;
_head = NULL;
_tail = NULL;
}

public:
bool Empty()
{
return _head==NULL;
}
void Push(const T&x)//尾插
{
Node<T>*newNode = new Node<T>(x);
if (_head == NULL)
{
_head = newNode;
_tail = newNode;
}
else
{
_tail->_next = newNode;
_tail = newNode;
}
}

void Pop()//头删
{
assert(_head);

if (_head == _tail)
{
delete _head;
_head = _tail = NULL;
}
else
{
Node<T>*del = _head;
_head = _head->_next;
delete del;
}
}

T& Front()//队首
{
assert(_head);

return _head->_data;
}

T& Back()//队尾
{
assert(_tail)

return _tail->_data;
}

private:
Node<T>* _head;
Node<T>* _tail;
};
void test()
{
Queue<int> q1;
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Push(5);
q1.Push(6);
q1.Push(7);
q1.Push(8);
Queue<int> q2;
q2 = q1;
Queue<int>q3(q2);
while (!q3.Empty())
{
cout << q3.Front() << " ";
q3.Pop();
}
}
int main()
{
test();
getchar();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构