您的位置:首页 > 其它

队列

2016-01-02 13:57 302 查看
#pragma once
#include<iostream>
#include<assert.h>
using namespace std;
template<class T>
struct Node
{
Node(const T& x)
:_data(x)
, _next(NULL)
{}
T _data;
Node<T>* _next;
};
template<class T>
class Queue
{
//先进先出
public:
Queue()
:_head(NULL)
, _tail(NULL)
{}
void Push(const T&x)
{
if (_head == NULL)
{
_head = new Node<T>(x);
_tail = _head;
}
else
{
_tail->_next = new Node<T>(x);
_tail = _tail->_next;
}
}
void Pop()
{
if (_head == _tail)
{
delete _head;
_head = _tail = NULL;
}
else
{
Node<T>*del = _head;
_head = _head->_next;
delete del;
}
}
bool IsEmpty()
{
return _head == NULL;
}
const T& Front()
{
assert(_head);//需判断
return _head->_data;
}
const T& Back()
{
assert(_tail);
return _tail->_data;
}
protected:
Node<T>* _head;
Node<T>* _tail;
};
void TestQueue()
{
Queue<int> q1;
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Push(5);
q1.Push(6);
while (!q1.IsEmpty())
{
cout << q1.Front() << " ";
q1.Pop();
}
cout << endl;
}
void  TestQueue1()
{
Queue<string> q2;
q2.Push("ab");
q2.Push("cd");
q2.Push("ef");
q2.Push("gh");
q2.Push("lm");
q2.Push("kl");
while (!q2.IsEmpty())
{
cout << q2.Front() << " ";
q2.Pop();
}
cout << endl;
}

#include<iostream>
using namespace std;
#include"Queue.h"
int main()
{
//栈的特点:后进先出,只能从尾部进行操作
//TestStack1();
TestQueue1();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  队列