用c语言利用队列和栈的基本操作将打指定对列中的元素进行逆转
时间: 2023-05-18 10:05:36 浏览: 135
以下是使用队列和栈的基本操作将指定队列中的元素进行逆转的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
void initStack(Stack *s) {
s->top = -1;
}
int isQueueEmpty(Queue *q) {
return q->front == q->rear;
}
int isQueueFull(Queue *q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
int isStackEmpty(Stack *s) {
return s->top == -1;
}
int isStackFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void enqueue(Queue *q, int x) {
if (isQueueFull(q)) {
printf("Queue is full.\n");
exit(1);
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_SIZE;
}
int dequeue(Queue *q) {
if (isQueueEmpty(q)) {
printf("Queue is empty.\n");
exit(1);
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return x;
}
void push(Stack *s, int x) {
if (isStackFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
void reverseQueue(Queue *q) {
Stack s;
initStack(&s);
while (!isQueueEmpty(q)) {
push(&s, dequeue(q));
}
while (!isStackEmpty(&s)) {
enqueue(q, pop(&s));
}
}
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
enqueue(&q, 4);
printf("Before reverse: ");
while (!isQueueEmpty(&q)) {
printf("%d ", dequeue(&q));
}
printf("\n");
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
enqueue(&q, 4);
reverseQueue(&q);
printf("After reverse: ");
while (!isQueueEmpty(&q)) {
printf("%d ", dequeue(&q));
}
printf("\n");
return 0;
}
```
运行结果:
```
Before reverse: 1 2 3 4
After reverse: 4 3 2 1
```
阅读全文