用两个栈完成队列的操作c语言
时间: 2023-05-29 18:05:17 浏览: 133
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *next;
} Node;
typedef struct queue {
Node *stack1;
Node *stack2;
} Queue;
Queue *createQueue() {
Queue *q = (Queue *)malloc(sizeof(Queue));
q->stack1 = NULL;
q->stack2 = NULL;
return q;
}
void push(Node **stack, int data) {
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data;
newNode->next = *stack;
*stack = newNode;
}
int pop(Node **stack) {
int data;
Node *temp = *stack;
*stack = (*stack)->next;
data = temp->data;
free(temp);
return data;
}
void enqueue(Queue *q, int data) {
push(&q->stack1, data);
}
int dequeue(Queue *q) {
if (q->stack1 == NULL && q->stack2 == NULL) {
printf("Queue is empty\n");
return -1;
}
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
push(&q->stack2, pop(&q->stack1));
}
}
return pop(&q->stack2);
}
int main() {
Queue *q = createQueue();
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
return 0;
}
阅读全文