总目录
1.基本实现
1.1 结构体构造
typedef struct LinkNode {
int data;
struct LinkNode *next;
} LinkNode;
typedef struct {
LinkNode *front, *rear;
} LinkQueue;
1.2 初始化
void InitQueue(LinkQueue &Q) {
Q.front = NULL;
Q.rear = NULL;
}
1.3 判空
bool Empty(LinkQueue Q) {
if(Q.front == NULL) {
return true;
} else {
return false;
}
}
1.4 入队
bool EnQueue(LinkQueue &Q, int x) {
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
if(s == NULL) {
return false;
}
s->data = x;
s->next = NULL;
if(Q.front == NULL) {
Q.front = s;
Q.rear = s;
} else {
Q.rear->next = s;
Q.rear = s;
}
return true;
}
1.5 出队
bool DeQueue(LinkQueue &Q, int &x) {
if(Q.front == NULL) {
return false;
}
LinkNode *p = Q.front;
x = p->data;
Q.front = p->next;
if(Q.rear == p) {
Q.front = NULL;
Q.rear = NULL;
}
free(p);
return true;
}
1.6 获取队头元素的值
bool GetHead(LinkQueue Q, int &x) {
if(Q.front == NULL) {
return false;
}
x = Q.front->data;
return true;
}
1.7 输出队列中所有元素
void PrintQueue(LinkQueue Q) {
if(Empty(Q)) {
printf("the queue is empty!\n");
}
while(!Empty(Q)) {
int x;
DeQueue(Q, x);
printf("dequeue:%d\n", x);
}
}
2.完整代码
#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) {
Q.front = NULL;
Q.rear = NULL;
}
bool Empty(LinkQueue Q) {
if(Q.front == NULL) {
return true;
} else {
return false;
}
}
bool EnQueue(LinkQueue &Q, int x) {
LinkNode *s = (LinkNode*)malloc(sizeof(LinkNode));
if(s == NULL) {
return false;
}
s->data = x;
s->next = NULL;
if(Q.front == NULL) {
Q.front = s;
Q.rear = s;
} else {
Q.rear->next = s;
Q.rear = s;
}
return true;
}
bool DeQueue(LinkQueue &Q, int &x) {
if(Q.front == NULL) {
return false;
}
LinkNode *p = Q.front;
x = p->data;
Q.front = p->next;
if(Q.rear == p) {
Q.front = NULL;
Q.rear = NULL;
}
free(p);
return true;
}
bool GetHead(LinkQueue Q, int &x) {
if(Q.front == NULL) {
return false;
}
x = Q.front->data;
return true;
}
void PrintQueue(LinkQueue Q) {
if(Empty(Q)) {
printf("the queue is empty!\n");
}
while(!Empty(Q)) {
int x;
DeQueue(Q, x);
printf("dequeue:%d\n", x);
}
}
int main() {
LinkQueue Q;
InitQueue(Q);
PrintQueue(Q);
int x;
EnQueue(Q, 3);
GetHead(Q, x);
printf("enqueue:%d\n", x);
x = 5;
EnQueue(Q, x);
printf("enqueue:%d\n", x);
x = 7;
EnQueue(Q, x);
printf("enqueue:%d\n", x);
PrintQueue(Q);
}
3.运行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/63db4947a5c440f2aebfca6475ca6df2.png)