1. 完整代码
/*
* @Author: JRAdmin
* @Date: 2021-11-04 07:16:09
* @LastEditTime: 2021-11-04 08:22:05
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \VSCode\Data_Structure\03_stack\LinkQueueDemo1.cpp
* LinkQueue (队列的链式实现) (带头结点)
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct LinkNode{
int data;
struct LinkNode *next;
}LinkNode;
typedef struct{
LinkNode *front, *rear;
}LinkQueue;
void InitQueue(LinkQueue &Q){
// 初始化时 front 、 rear 都要指向头结点
Q.front = Q.rear = (LinkNode *)malloc(sizeof(LinkNode));
Q.front->next = NULL;
}
bool Empty(LinkQueue Q){
if(Q.front == Q.rear){ // 或者判断: Q.front -> next == NULL
return true;
}
return false;
}
bool EnQueue(LinkQueue &Q, int e){
LinkNode *newNode = (LinkNode *)malloc(sizeof(LinkNode));
if(newNode == NULL){
return false;
}
newNode->data = e;
newNode->next = NULL;
Q.rear->next = newNode;
Q.rear = newNode;
return true;
}
bool DeQueue(LinkQueue &Q, int &e){
if(Empty(Q)){
return false;
}
LinkNode *p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if(Q.rear == p){ // 此次为最后一个结点出队时
Q.rear = Q.front; // 修改 rear 指针 变回空队列状态
}
free(p);
return true;
}
void TraverseQueue(LinkQueue Q){
LinkNode *p = Q.front->next;
while(p != NULL){
printf("%d\t",p->data);
p = p->next;
}
printf("\n");
}
int main(){
LinkQueue Q;
LinkNode LN;
printf("sizeof(Q) = %d\n",sizeof(Q));
printf("sizeof(LN) = %d\n",sizeof(LN));
InitQueue(Q);
printf("Empty(Q) = %d\n",Empty(Q));
printf("EnQueue(Q) :\t");
for(int i = 0; i < 5; i++){
EnQueue(Q,i+1);
}
TraverseQueue(Q);
int e1;
DeQueue(Q,e1);
printf("DeQueue(Q,e1) = %d\n",e1);
TraverseQueue(Q);
for(int i = 0; i < 4; i++){
DeQueue(Q,e1);
printf("DeQueue(Q,e1) = %d\n",e1);
TraverseQueue(Q);
}
printf("EnQueue(Q) agin :\t");
for(int i = 0; i < 5; i++){
EnQueue(Q,i+1);
}
TraverseQueue(Q);
return 0;
}
2. 运行结果
main函数中对链队列进行了多种操作进行测试,可自行增删;