用c语言编写程序 设Q是一个队列 S是一个空栈 实现将队列中的元素逆置的算法
时间: 2024-05-25 16:16:39 浏览: 18
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
int data[MAXSIZE];
int front, rear;
} Queue;
typedef struct {
int data[MAXSIZE];
int top;
} Stack;
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
void initStack(Stack *s) {
s->top = -1;
}
int isEmptyQueue(Queue *q) {
return (q->front == q->rear);
}
int isEmptyStack(Stack *s) {
return (s->top == -1);
}
int isFullQueue(Queue *q) {
return ((q->rear + 1) % MAXSIZE == q->front);
}
int isFullStack(Stack *s) {
return (s->top == MAXSIZE - 1);
}
int enQueue(Queue *q, int x) {
if (isFullQueue(q)) {
printf("Queue is full.\n");
return 0;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAXSIZE;
return 1;
}
int deQueue(Queue *q, int *x) {
if (isEmptyQueue(q)) {
printf("Queue is empty.\n");
return 0;
}
*x = q->data[q->front];
q->front = (q->front + 1) % MAXSIZE;
return 1;
}
int push(Stack *s, int x) {
if (isFullStack(s)) {
printf("Stack is full.\n");
return 0;
}
s->top++;
s->data[s->top] = x;
return 1;
}
int pop(Stack *s, int *x) {
if (isEmptyStack(s)) {
printf("Stack is empty.\n");
return 0;
}
*x = s->data[s->top];
s->top--;
return 1;
}
void reverseQueue(Queue *q) {
Stack s;
initStack(&s);
int x;
while (!isEmptyQueue(q)) {
deQueue(q, &x);
push(&s, x);
}
while (!isEmptyStack(&s)) {
pop(&s, &x);
enQueue(q, x);
}
}
int main() {
Queue q;
initQueue(&q);
enQueue(&q, 1);
enQueue(&q, 2);
enQueue(&q, 3);
enQueue(&q, 4);
printf("Before reverse: ");
int x;
while (!isEmptyQueue(&q)) {
deQueue(&q, &x);
printf("%d ", x);
}
printf("\n");
reverseQueue(&q);
printf("After reverse: ");
while (!isEmptyQueue(&q)) {
deQueue(&q, &x);
printf("%d ", x);
}
printf("\n");
return 0;
}