//链队列
#include <stdio.h>
#include <iostream>
using namespace std;
#define qElemType int
typedef struct qNode{
qElemType data;
qNode *next;
}*qPtr;
typedef struct queue{
qPtr front;
qPtr rear;
};
//初始化队列;front,rear指针都指向头结点
void initQueue(queue &Q){
Q.front=Q.rear=new qNode;
}
//判空:返回1表示空队列,返回0,则不是空队列
int isEmpty(queue Q){
return Q.front==Q.rear;
}
//插入元素到队列
void enQueue(queue &Q,qElemType e){
qPtr newNode =new qNode;
newNode->data=e;
Q.rear->next=newNode;
Q.rear=newNode;
}
//在队列中删除元素
void deQueue(queue &Q,qElemType &e){
if(isEmpty(Q)){
cout<<"队列为空"<<endl;
return;
}
//保存被删元素
e=Q.front->next->data;
//保存被删元素指针
qPtr temp=Q.front->next;
Q.front->next=Q.front->next->next;
//删除被删元素指针
delete temp;
}
//打印队列中的元素
void printFrontAndRear(queue Q){
cout<<"队列的第一个元素为:";
cout<<Q.front->next->data<<endl;
cout<<"队列的最后一个元素为:";
cout<<Q.rear->data<<endl;
}
int main(){
queue Q;
initQueue(Q);
enQueue(Q,1);
enQueue(Q,2);
enQueue(Q,3);
enQueue(Q,4);
enQueue(Q,5);
printFrontAndRear(Q);
qElemType val;
deQueue(Q,val);
cout<<"队列中被删除的元素为:"<<val<<endl;
printFrontAndRear(Q);
}
在这里插入代码片
运行结果截图: