队列提供了以下操作:
q.empty() //如果队列为空返回true,否则返回false
q.size() //返回队列中元素的个数
q.pop() //删除队列首元素的值,但不返回其值
q.front() //返回队列首元素的值,但不删除其值
q.push() //在队尾压入新元素
q.back() //返回队尾元素的值,但不删除其值
模拟实现:
/*Queue.cpp*/
#include <iostream>
using namespace std;
template<class T>
struct Node
{
Node(const T& d)
:_data(d)
,_next(NULL)
{}
T _data;
struct Node* _next;
};
template<class T>
class LinkList
{
public:
LinkList()
:_head(NULL)
,_tail(NULL)
{}
~LinkList()
{
if(_head == NULL)
{
cout<<"List is empty!!"<<endl;
return;
}
Node<T>* cur = _head;
while(cur != NULL)
{
Node<T>* del = cur;
cur = cur->_next;
delete del;
del = NULL;
}
delete cur;
_head = NULL;
_tail = NULL;
}
public:
void Display()
{
Node<T>* cur = _head;
while(cur)
{
cout<<cur->_data<<"-->";
cur = cur->_next;
}
cout<<"Nvl."<<endl;
}
void PushBack(const T& d)
{
Node<T>* NewNode = new Node<T>(d);
if(_head == NULL)
{
_head = NewNode;
_tail = _head;
}
else
{
_tail->_next = NewNode;
_tail = NewNode;
}
}
void PopFront()
{
if(_head == NULL)
{
cout<<"Queue is empty!!"<<endl;
return;
}
Node<T>* del =_head;
_head = _head->_next;
delete del;
del = NULL;
}
int GetListLength()
{
Node<T>* cur = _head;
int count = 0;
while(cur)
{
count++;
cur = cur->_next;
}
return count;
}
T& GetHeadValue()
{
if(_head == NULL)
{
cout<<"Queue is empty!!"<<endl;
exit(1);
}
return _head->_data;
}
T& GetTailValue()
{
if(_head == NULL)
{
cout<<"Queue is empty!!"<<endl;
exit(1);
}
return _tail->_data;
}
bool JudgeIsEmpty()
{
if(_head == NULL)
{
return true;
}
return false;
}
private:
Node<T>* _head;
Node<T>* _tail;
};
template<class T, class Container>
class Queue
{
public:
void Show()
{
_con.Display();
}
void Push(const T& q)
{
_con.PushBack(q);
}
void Pop()
{
_con.PopFront();
}
int Size()
{
return _con.GetListLength();
}
const T& Front()
{
return _con.GetHeadValue();
}
const T& Back()
{
return _con.GetTailValue();
}
bool Empty()
{
return _con.JudgeIsEmpty();
}
private:
Container _con;
};
int main()
{
Queue<int,LinkList<int> > q1;
q1.Push(1);
q1.Push(2);
q1.Push(3);
q1.Push(4);
q1.Push(5);
q1.Show();
q1.Pop();
q1.Show();
int size = q1.Size();
cout<<"size = "<<size<<endl;
int retTail = q1.Back();
cout<<"retTail = "<<retTail<<endl;
int retHead = q1.Front();
cout<<"retHead = "<<retHead<<endl;
bool result = q1.Empty();
cout<<"result = "<<result<<endl;
system("pause");
return 0;
}
结果:
转载于:https://blog.51cto.com/xujiafan/1758089