用C语言 编写一个算法,把队列逆转。用C语言写出完整代码
时间: 2023-06-06 12:07:46 浏览: 95
Sure, here is the complete code to reverse a queue in C:
```
#include <stdio.h>
#include <stdlib.h>
/* Define structure for queue */
struct Queue {
int front, rear;
int* items;
int size;
};
/* Create a new empty queue */
struct Queue* newQueue(int size) {
struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->front = -1;
queue->rear = -1;
queue->size = size;
queue->items = (int*) malloc(queue->size * sizeof(int));
return queue;
}
/* Check if queue is full */
int isFull(struct Queue* queue) {
return queue->rear == queue->size - 1;
}
/* Check if queue is empty */
int isEmpty(struct Queue* queue) {
return queue->front == -1;
}
/* Add element to back of queue */
void enqueue(struct Queue* queue, int item) {
if (isFull(queue))
return;
if (queue->front == -1)
queue->front = 0;
queue->rear++;
queue->items[queue->rear] = item;
}
/* Remove and return element from front of queue */
int dequeue(struct Queue* queue) {
if (isEmpty(queue))
return -1;
int item = queue->items[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return item;
}
/* Reverse the queue */
void reverseQueue(struct Queue* queue) {
int temp;
while (!isEmpty(queue)) {
temp = dequeue(queue);
enqueue(queue, temp);
}
while (queue->rear != queue->front) {
temp = dequeue(queue);
enqueue(queue, temp);
}
}
int main() {
/* Create a queue */
struct Queue* queue = newQueue(5);
/* Add elements to queue */
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
enqueue(queue, 4);
enqueue(queue, 5);
/* Reverse the queue */
reverseQueue(queue);
/* Print reversed queue */
printf("Reversed Queue: ");
while (!isEmpty(queue)) {
printf("%d ", dequeue(queue));
}
printf("\n");
return 0;
}
```
Hope that helps!
阅读全文