用栈实现队列C语言代码
时间: 2024-06-15 14:03:58 浏览: 104
使用栈实现队列的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义栈结构
typedef struct {
int* data; // 存储数据的数组
int top; // 栈顶指针
int maxSize; // 栈的最大容量
} Stack;
// 初始化栈
void initStack(Stack* stack, int maxSize) {
stack->data = (int*)malloc(sizeof(int) * maxSize);
stack->top = -1;
stack->maxSize = maxSize;
}
// 判断栈是否为空
int isEmpty(Stack* stack) {
return stack->top == -1;
}
// 判断栈是否已满
int isFull(Stack* stack) {
return stack->top == stack->maxSize - 1;
}
// 入栈操作
void push(Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack is full!\n");
return;
}
stack->data[++stack->top] = value;
}
// 出栈操作
int pop(Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty!\n");
return -1;
}
return stack->data[stack->top--];
}
// 使用栈实现队列
typedef struct {
Stack* inStack; // 入队栈
Stack* outStack; // 出队栈
} MyQueue;
// 初始化队列
void initQueue(MyQueue* queue, int maxSize) {
queue->inStack = (Stack*)malloc(sizeof(Stack));
queue->outStack = (Stack*)malloc(sizeof(Stack));
initStack(queue->inStack, maxSize);
initStack(queue->outStack, maxSize);
}
// 入队操作
void enqueue(MyQueue* queue, int value) {
if (isFull(queue->inStack)) {
printf("Queue is full!\n");
return;
}
// 将元素压入入队栈
push(queue->inStack, value);
}
// 出队操作
int dequeue(MyQueue* queue) {
if (isEmpty(queue->outStack)) {
// 如果出队栈为空,则将入队栈的元素依次弹出并压入出队栈
while (!isEmpty(queue->inStack)) {
push(queue->outStack, pop(queue->inStack));
}
}
return pop(queue->outStack);
}
int main() {
MyQueue queue;
initQueue(&queue, 5);
enqueue(&queue, 1);
enqueue(&queue, 2);
enqueue(&queue, 3);
printf("%d\n", dequeue(&queue));
printf("%d\n", dequeue(&queue));
enqueue(&queue, 4);
enqueue(&queue, 5);
printf("%d\n", dequeue(&queue));
printf("%d\n", dequeue(&queue));
return 0;
}
```
阅读全文