代码如下:
#include<iostream>
using namespace std;
#include<string>
template<class T>
struct Node {
T data;
Node<T>* next;
};
template<class T>
class Linkqueue {
public:
Linkqueue();
~Linkqueue();
void Inqueue(T x);
T Outqueue();
T Getqueue();
int Empty();
private:
Node<T>* front, * rear;
};
//初始化
template<class T>
Linkqueue<T>::Linkqueue() {
Node<T>* s = NULL;
s = new Node<T>;
s->next = NULL;
front = rear = s;
}
//析构函数
template<class T>
Linkqueue<T>::~Linkqueue() {
Node<T>* p = NULL;
while (front!= NULL) {
p = front;
front = front->next;
delete p;
}
}
//入队
template<class T>
void Linkqueue<T>::Inqueue(T x) {
Node<T>* s = NULL;
s = new Node<T>;
s->data = x;
s->next = NULL;
rear->next = s;
rear = s;
}
//出队
template<class T>
T Linkqueue<T>::Outqueue() {
if (rear == front) { cout << "下溢" << endl; }
Node<T>* p;
p = front->next;
T x = p->data;
front->next =p->next;
if (p->next == rear) { cout << "出队前队列长度为1" << endl; }
delete p;
return x;
}
//取队头元素
template<class T>
T Linkqueue<T>::Getqueue() {
if (front == rear) { cout << "队为空无法取队头" << endl; }
cout << front->next->data << endl;
return front->next->data;
}
//判空
template<class T>
int Linkqueue<T>::Empty() {
if (front == rear) {
cout << "队列为空" << endl;
}
else { cout << "队列不为空" << endl; }
}
int main() {
Linkqueue<string>L;
L.Inqueue("李华");
L.Getqueue();
}