用C语言实现两个队列A和B来实现栈的功能
时间: 2024-04-14 21:27:52 浏览: 95
C语言实现栈与队列
5星 · 资源好评率100%
以下是使用两个队列 A 和 B 实现栈功能的 C 语言示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int *data;
int top;
int capacity;
} Stack;
typedef struct {
int *data;
int front;
int rear;
int capacity;
} Queue;
Queue* createQueue(int capacity) {
Queue *queue = (Queue*)malloc(sizeof(Queue));
queue->data = (int*)malloc(capacity * sizeof(int));
queue->front = 0;
queue->rear = -1;
queue->capacity = capacity;
return queue;
}
int isEmpty(Queue *queue) {
return queue->rear < queue->front;
}
int isFull(Queue *queue) {
return queue->rear >= queue->capacity - 1;
}
void enqueue(Queue *queue, int value) {
if (isFull(queue)) {
printf("Queue is full!\n");
return;
}
queue->data[++queue->rear] = value;
}
int dequeue(Queue *queue) {
if (isEmpty(queue)) {
printf("Queue is empty!\n");
return -1;
}
return queue->data[queue->front++];
}
void push(Stack *stack, int value) {
enqueue(stack->data, value);
stack->top++;
}
int pop(Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty!\n");
return -1;
}
while (stack->top > 0) {
int temp = dequeue(stack->data);
enqueue(stack->data, temp);
stack->top--;
}
int result = dequeue(stack->data);
while (!isEmpty(stack->data)) {
int temp = dequeue(stack->data);
enqueue(stack->data, temp);
stack->top++;
}
return result;
}
int top(Stack *stack) {
if (stack->top == -1) {
printf("Stack is empty!\n");
return -1;
}
while (stack->top > 0) {
int temp = dequeue(stack->data);
enqueue(stack->data, temp);
stack->top--;
}
int result = dequeue(stack->data);
enqueue(stack->data, result);
stack->top++;
while (!isEmpty(stack->data)) {
int temp = dequeue(stack->data);
enqueue(stack->data, temp);
stack->top++;
}
return result;
}
int main() {
int capacity = 10;
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->data = createQueue(capacity);
stack->top = -1;
stack->capacity = capacity;
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("Top element: %d\n", top(stack));
printf("Popped element: %d\n", pop(stack));
printf("Top element: %d\n", top(stack));
free(stack->data);
free(stack);
return 0;
}
```
这段代码定义了两个结构体,`Stack` 表示栈,`Queue` 表示队列。使用队列实现栈的入栈(`push`)、出栈(`pop`)、获取栈顶元素(`top`)操作。在 `main()` 函数中进行了简单的测试。
请注意,这段代码只是一个示例,可能还有改进的空间,比如对输入错误的处理或者动态扩展队列的容量等。
阅读全文