用C语言写一个程序:两个栈实现一个队列
时间: 2024-02-11 07:02:16 浏览: 31
以下是用C语言实现两个栈实现一个队列的程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct stack {
int top;
int capacity;
int* array;
} Stack;
typedef struct queue {
Stack* stack1;
Stack* stack2;
} Queue;
Stack* createStack(int capacity) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->capacity = capacity;
stack->top = -1;
stack->array = (int*)malloc(stack->capacity * sizeof(int));
return stack;
}
int isStackEmpty(Stack* stack) {
return stack->top == -1;
}
int isStackFull(Stack* stack) {
return stack->top == stack->capacity - 1;
}
void push(Stack* stack, int item) {
if (isStackFull(stack)) {
printf("Stack is full.\n");
return;
}
stack->array[++stack->top] = item;
}
int pop(Stack* stack) {
if (isStackEmpty(stack)) {
printf("Stack is empty.\n");
return -1;
}
return stack->array[stack->top--];
}
void enqueue(Queue* queue, int item) {
push(queue->stack1, item);
}
int dequeue(Queue* queue) {
if (isStackEmpty(queue->stack1) && isStackEmpty(queue->stack2)) {
printf("Queue is empty.\n");
return -1;
}
if (isStackEmpty(queue->stack2)) {
while (!isStackEmpty(queue->stack1)) {
int item = pop(queue->stack1);
push(queue->stack2, item);
}
}
return pop(queue->stack2);
}
int main() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->stack1 = createStack(100);
queue->stack2 = createStack(100);
enqueue(queue, 1);
enqueue(queue, 2);
enqueue(queue, 3);
printf("%d dequeued from queue.\n", dequeue(queue));
printf("%d dequeued from queue.\n", dequeue(queue));
printf("%d dequeued from queue.\n", dequeue(queue));
free(queue->stack1->array);
free(queue->stack1);
free(queue->stack2->array);
free(queue->stack2);
free(queue);
return 0;
}
```