队列
作者:Lew's Personal Blog 发布于:2020-1-6 11:12 Monday 分类:C/C++
#include<iostream>#include<string>
using namespace std;
template <typename T>
struct Node
{
T value;
Node<T> *next;
Node<T>(){ next = NULL; }
};
template <typename T>
class MyQueue
{
private:
unsigned int num;//记录队列的长度
Node<T> *first;
Node<T> *last;
public:
MyQueue();
~MyQueue();
unsigned int size();
void push(T element);
void pop();
bool empty();
T back();
T front();
};
template <typename T>
MyQueue<T>::MyQueue()//构造函数
{
num = 0;
first = NULL;
last = NULL;
}
template <typename T>
MyQueue<T>::~MyQueue()//析构函数
{
while (!empty())
{
pop();
}
}
template <typename T>
unsigned int MyQueue<T>::size()
{
return num;
}
template <typename T>
bool MyQueue<T>::empty()//判断是否为空
{
return (0 == num);
}
template <typename T>
void MyQueue<T>::push(T element)
{
Node<T> *temp = new Node<T>;
temp->next = NULL;
temp->value = element;
if (0 == this->num)
{//注意判断条件先后顺序
first = temp;
last = temp;
}
else
{
last->next = temp;
last = temp;
}
(this->num)++;
}
template <typename T>
void MyQueue<T>::pop()
{
if (0 == this->num)
{
cout << "No elements in the queue!" << endl;
}
else if (1 == this->num)//why
{
delete first;
first = NULL;
last = NULL;
this->num = 0;
}
else
{
Node<T> *temp = first;
first = first->next;
delete temp;
(this->num)--;
}
}
template <typename T>
T MyQueue<T>::back()
{
if (0 == this->num)
{
cout << "No elements in the queue!" << endl;
return NULL;
}
return last->value;
}
template <typename T>
T MyQueue<T>::front()
{
if (0 == this->num)
{
cout << "No elements in the queue!" << endl;
return NULL;
}
return first->value;
}
int main(int argc, char **argv)
{
MyQueue<string> q;
q.push("Hello world");
q.push("China");
cout << q.front() << endl;
cout << q.size() << endl;
cout << q.back() << endl;
q.pop();
cout << q.empty() << endl;
cout << q.back() << endl;
cout << q.front() << endl; //first and last are point to the similer element
q.pop();
cout << q.size() << endl;
cout << q.empty() << endl; //返回1
system("pause");
return 0;
}
标签: 队列
« 上一篇 二叉树搜索树基本操作 | 单词拆分 下一篇»