给出c语言使用两个栈实现队列的代码
时间: 2023-11-19 16:04:33 浏览: 113
python 实现 用两个栈实现队列
好的,以下是使用两个栈实现队列的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int stack1[MAX_SIZE];
int stack2[MAX_SIZE];
int top1 = -1;
int top2 = -1;
void push(int stack[], int *top, int value) {
if (*top == MAX_SIZE - 1) {
printf("Stack is full\n");
return;
}
stack[++(*top)] = value;
}
int pop(int stack[], int *top) {
if (*top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[(*top)--];
}
void enqueue(int value) {
push(stack1, &top1, value);
}
int dequeue() {
if (top1 == -1 && top2 == -1) {
printf("Queue is empty\n");
return -1;
}
if (top2 == -1) {
while (top1 != -1) {
push(stack2, &top2, pop(stack1, &top1));
}
}
return pop(stack2, &top2);
}
int main() {
enqueue(1);
enqueue(2);
enqueue(3);
printf("%d\n", dequeue());
printf("%d\n", dequeue());
printf("%d\n", dequeue());
printf("%d\n", dequeue());
return 0;
}
```
希望能对你有所帮助!
阅读全文