用C语言编写一个算法,把输入的队列逆转并输出。用C语言写出完整代码
时间: 2023-06-06 21:07:45 浏览: 86
将数组逆序排列,C语言实现。
Sure, here's the code:
```
#include <stdio.h>
#define MAX_SIZE 100 // maximum size of the queue
// functions to perform enqueue and dequeue operations
void enqueue(int queue[], int *rear, int value) {
queue[++(*rear)] = value; // increment rear index and add value to the queue
}
int dequeue(int queue[], int *front) {
return queue[(*front)++]; // increment front index and return the value at that index
}
void reverse_queue(int queue[], int size) {
int front = 0, rear = size - 1; // initialize front and rear pointers
while (front < rear) { // swap elements until front and rear pointers meet in the middle
int temp = queue[front];
queue[front] = queue[rear];
queue[rear] = temp;
front++;
rear--;
}
}
int main() {
int queue[MAX_SIZE]; // initialize array to store queue elements
int front = -1, rear = -1; // initialize front and rear pointers
// get input values and enqueue them
printf("Enter queue elements (end with -1):\n");
int value;
while (1) {
scanf("%d", &value);
if (value == -1) break; // stop getting input at -1
enqueue(queue, &rear, value);
}
// reverse the queue
reverse_queue(queue, rear + 1);
// dequeue and print each element in the reversed queue
printf("Reversed queue elements:\n");
while (front < rear) {
int value = dequeue(queue, &front);
printf("%d ", value);
}
printf("\n");
return 0;
}
```
阅读全文