字画草图:
这里头尾指针是指针并不是普通队列的下标。
动态分配内存空间,所以不存在假溢出问题,也就不用循环队列
#include <iostream>
using namespace std;
/*
入队:
判断是否为空,即front为空,若为空,头尾指针指向插入元素
不为空,移动尾指针插入即可
出队;
判断是否为空
不为空则判断是否为队中的最后一个元素,若是最后一个元素,则头尾指针都指向空
都不符合正常移动头指针出队即可
*/
//链表节点结构体
struct Node
{
int data;
Node *next;
};
class ListQueue{
protected:
Node* front;
Node* rear;
public:
//初始化
void init(){
this->front = NULL;
this->rear = NULL;
}
//入队
void enQueue(int ele){
Node* cur = new Node;
cur->data = ele;
if(this->front == NULL){//队列为空,头尾指针指向第一个元素
this->front = cur;
this->rear = cur;
}else{
//不为空。移动尾指针入队
this->rear->next = cur;
this->rear = cur;//rear = rear->next;
}
}
//出队
void deQueue(int &num){
//判断是否队空
if(this->front == NULL){
cout<<"空队\n";
return ;
}
//是否只有一个元素
if(this->front == this->rear){
Node* p = this->front;
num = p->data;
delete p;
this->front = NULL;
this->rear = NULL;
}else{
//移动头指针出队
Node* p = this->front;
num = p->data;
this->front = this->front->next;
delete p;
}
}
};
int main(){
ListQueue q;
q.init();
for(int i=1; i<=10; i++){
q.enQueue(i);
}
for(int i=1; i<=10; i++){
int num;
q.deQueue(num);
cout<<num<<" ";
}
return 0;
}