以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素。
程序员文章站
2024-03-21 14:15:16
...
出队的时候一定要注意是不是最后一个元素出队。
//假设以带头结点的循环链表表示队列,并且只设一个指针指向队尾元素结点,试编写相
//应的初始化、入队以及出队算法。
#include<stdio.h>
#include<stdlib.h>
typedef enum { ERROR, OK, EMPTY, NOTEMPTY } bool;
typedef int Status;
typedef int ElemType;
typedef struct Node {
ElemType data;
struct Node *next;
}Queue, *LinkQueue;
LinkQueue Rear;
bool InitQueue(LinkQueue Q) {
Q->next = Q;
Rear = Q;
return OK;
}
bool JudgeQueue(LinkQueue Q) {
if (Rear == Q) {
printf("Queue is Empty\n");
return EMPTY;
}
printf("Queue is not empty\n");
return NOTEMPTY;
}
bool EnQueue(LinkQueue Q, ElemType e) {
LinkQueue p;
p = (LinkQueue)malloc(sizeof(Queue));
if (p == NULL)
return ERROR;
p->data = e;
p->next = Rear->next;
Rear->next = p;
Rear = p;
return OK;
}
bool DeQueue(LinkQueue Q, ElemType *e) {
if (Rear == Q) {
printf("Queue is Empty\n");
return ERROR;
}
LinkQueue p;
p = Rear->next->next;
*e = p->data;
Rear->next->next = p->next;
if (Rear == p)
Rear = Q;
free(p);
return OK;
}
//测试
int main() {
LinkQueue Q = NULL;
Q = (LinkQueue)malloc(sizeof(Queue));
bool flag;
flag = InitQueue(Q);
if (flag == ERROR)
printf("Init RROR\n");
else if (flag == OK)
printf("Init OK\n");
JudgeQueue(Q);
ElemType e;
for (int i = 0; i < 4; i++) {
printf("请输入:\n");
scanf_s("%d", &e);
flag = EnQueue(Q, e);
if (flag == OK)
printf("Enter OK\n");
else
printf("Enter ERROR\n");
}
JudgeQueue(Q);
for (int i = 0; i < 3; i++) {
flag = DeQueue(Q, &e);
if (flag == ERROR) {
printf("Queue is EmPty\n");
continue;
}
if (flag == OK) {
printf("%d\n", e);
}
JudgeQueue(Q);
}
for (int i = 0; i < 4; i++) {
printf("请输入:\n");
scanf_s("%d", &e);
flag = EnQueue(Q, e);
if (flag == OK)
printf("Enter OK\n");
else
printf("Enter ERROR\n");
}
JudgeQueue(Q);
for (int i = 0; i < 5; i++) {
flag = DeQueue(Q, &e);
if (flag == ERROR) {
printf("Queue is EmPty\n");
continue;
}
if (flag == OK) {
printf("%d\n", e);
}
JudgeQueue(Q);
}
}
下一篇: js checkbox 全选 取消全选