用C或C++描述循环队列每种操作在顺序循环队列或链队上的实现
时间: 2024-05-05 17:20:56 浏览: 94
以下是用C语言描述循环队列每种操作在顺序循环队列上的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct {
int data[MAXSIZE];
int front, rear;
} SqQueue;
void InitQueue(SqQueue *q) {
q->front = q->rear = 0;
}
int QueueLength(SqQueue q) {
return (q.rear - q.front + MAXSIZE) % MAXSIZE;
}
int EnQueue(SqQueue *q, int x) {
if ((q->rear + 1) % MAXSIZE == q->front) {
printf("Queue is full.\n");
return 0;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
return 1;
}
int DeQueue(SqQueue *q, int *x) {
if (q->front == q->rear) {
printf("Queue is empty.\n");
return 0;
}
*x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return 1;
}
int main() {
SqQueue q;
InitQueue(&q);
EnQueue(&q, 1);
EnQueue(&q, 2);
EnQueue(&q, 3);
int len = QueueLength(q);
printf("Queue length: %d\n", len);
int x;
DeQueue(&q, &x);
printf("DeQueue: %d\n", x);
len = QueueLength(q);
printf("Queue length: %d\n", len);
return 0;
}
```
以下是用C语言描述循环队列每种操作在链队列上的实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct QNode {
int data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct {
QueuePtr front, rear;
} LinkQueue;
void InitQueue(LinkQueue *q) {
q->front = q->rear = (QueuePtr)malloc(sizeof(QNode));
if (!q->front) {
printf("Malloc failure.\n");
exit(1);
}
q->front->next = NULL;
}
int QueueLength(LinkQueue q) {
int len = 0;
QueuePtr p = q.front->next;
while (p) {
len++;
p = p->next;
}
return len;
}
int EnQueue(LinkQueue *q, int x) {
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if (!p) {
printf("Malloc failure.\n");
exit(1);
}
p->data = x;
p->next = NULL;
q->rear->next = p;
q->rear = p;
return 1;
}
int DeQueue(LinkQueue *q, int *x) {
if (q->front == q->rear) {
printf("Queue is empty.\n");
return 0;
}
QueuePtr p = q->front->next;
*x = p->data;
q->front->next = p->next;
if (q->rear == p) {
q->rear = q->front;
}
free(p);
return 1;
}
int main() {
LinkQueue q;
InitQueue(&q);
EnQueue(&q, 1);
EnQueue(&q, 2);
EnQueue(&q, 3);
int len = QueueLength(q);
printf("Queue length: %d\n", len);
int x;
DeQueue(&q, &x);
printf("DeQueue: %d\n", x);
len = QueueLength(q);
printf("Queue length: %d\n", len);
return 0;
}
```
阅读全文