用C语言编写一个程序,在这个程序中完成如下功能: (1)建立一个循环顺序队列,并在此循环顺序队列上实现入队、出队和队列的判空操作。 (2)建立一个仅用尾指针标识的循环链队列,并在此循环链队列上实现入队、出队操作。
时间: 2024-11-04 09:13:31 浏览: 46
在C语言中,我们可以使用数组实现循环顺序队列,而使用链表实现循环链队列。以下是两个简单示例:
**1. 循环顺序队列(Circular Sequential Queue, CSQ)**
```c
#include <stdio.h>
#define MAX_SIZE 10
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
// 函数声明
void enqueue(Queue *q);
int dequeue(Queue *q);
int is_empty(Queue *q);
// 实现
void enqueue(Queue *q, int value) {
if ((q->rear + 1) % MAX_SIZE == q->front) {
printf("Queue is full.\n");
} else {
q->data[q->rear] = value;
q->rear = (q->rear + 1) % MAX_SIZE;
if (q->front == q->rear)
printf("Enqueue operation: Queue is now empty.\n");
else
printf("Enqueue operation: Value %d added to the queue.\n", value);
}
}
int dequeue(Queue *q) {
if (is_empty(q)) {
printf("Dequeue operation: Queue is already empty.\n");
return -1; // 返回特殊值表示队列为空
} else {
int value = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
printf("Dequeue operation: Removed value %d from the queue.\n", value);
return value;
}
}
int is_empty(Queue *q) {
return (q->front == q->rear);
}
int main() {
Queue q;
q.front = q.rear = 0;
// 测试
enqueue(&q, 5);
enqueue(&q, 10);
dequeue(&q);
is_empty(&q); // 输出结果
return 0;
}
```
**2. 循环链队列(Circular Linked Queue, CLQ)**
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* head;
Node* tail;
} LinkedList;
// 函数声明
void push(LinkedList* list, int value);
int pop(LinkedList* list);
int is_empty(LinkedList* list);
// 实现
void push(LinkedList* list, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = value;
newNode->next = list->head;
if (list->tail == list->head)
list->tail = newNode;
else
list->tail->next = newNode;
list->tail = newNode;
if (is_empty(list))
printf("Push operation: Queue is now empty.\n");
else
printf("Push operation: Added value %d to the queue.\n", value);
}
int pop(LinkedList* list) {
if (is_empty(list)) {
printf("Pop operation: Queue is already empty.\n");
return -1; // 返回特殊值表示队列为空
} else {
int value = list->head->data;
Node* temp = list->head;
list->head = list->head->next;
free(temp);
if (list->head == list->tail)
list->tail = NULL;
printf("Pop operation: Removed value %d from the queue.\n", value);
return value;
}
}
int is_empty(LinkedList* list) {
return (list->head == NULL);
}
int main() {
LinkedList list;
list.head = list.tail = NULL;
// 测试
push(&list, 5);
push(&list, 10);
pop(&list);
is_empty(&list); // 输出结果
return 0;
}
```
阅读全文