【实现类】
template<class T>
struct Node{
T data;
Node *next;
};
template<class T>
class linkQueue{
public:
linkQueue();
~linkQueue();
void push(T x);//入队
T pop();//出队
bool empty();//判断队列是否为空
T getFront();//获取队首元素
private:
Node<T> *head,*tail;
};
【构造函数】
template <class T>
linkQueue<T>::linkQueue(){
Node<T> s=new Node<T>;//创建一个头结点
s->next=NULL;
head=tail=s;//队首与队尾指针指向头结点
}
【析构函数】
template<class T>
linkQueue<T>::~linkQueue(){
while(head!=NULL){
Node<T> q=head;//暂存要被释放的结点
head=head->next;//first指向要被释放的结点的下一个结点
delete q;//删除结点
}
}
【入队】
template <class T>
void linkQueue<T>::push(T x){//入队
Node<T> s=new Node<T>;//新申请结点
s->data=x;
s->next=NULL;
tail->next=s;//结点s插到队尾
tail=s;
}
【出队】
template <class T>
T linkQueue<T>::pop(){//出队
if(head==tail)
throw "下溢";
Node<T> p=new Node<T>;
p=head->next;
T x=p->data;//暂存出队结点
head->next=p->next;
if(p->next==NULL)//判断队列此时是否为空
tail=head;
delete p;
return x;
}
【判断是否为空】
template<class T>
bool linkQueue<T>::empty(){//判断队列是否为空
if(head==tail)
return true;
return false;
}
【获取队首元素】
template<class T>
T linkQueue<T>::getFront(){//获取队首元素
if(head==tail)
throw "下溢";
return head->next->data;
}