#include <stdio.h>
#include <stdlib.h>
#define MAX 100
typedef struct Stack {
int arr[MAX];
int top;
} Stack;
void initStack(Stack* s) {
s->top = -1;
}
int isEmpty(Stack* s) {
return s->top == -1;
}
int isFull(Stack* s) {
return s->top == MAX - 1;
}
void push(Stack* s, int val) {
if (isFull(s)) {
printf("Stack overflow\n");
return;
}
s->arr[++(s->top)] = val;
}
int pop(Stack* s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
return -1;
}
return s->arr[(s->top)--];
}
typedef struct Queue {
Stack s1;
Stack s2;
} Queue;
void initQueue(Queue* q) {
initStack(&q->s1);
initStack(&q->s2);
}
void enqueue(Queue* q, int val) {
push(&q->s1, val); // push new element onto s1
}
int dequeue(Queue* q) {
if (isEmpty(&q->s2)) { // if s2 empty, move all from s1 to s2
while (!isEmpty(&q->s1)) {
int x = pop(&q->s1); // pop from s1
push(&q->s2, x); // push onto s2
}
}
return pop(&q->s2); // pop from s2 is dequeue
}
int main() {
Queue q;
initQueue(&q);
enqueue(&q, 1);
enqueue(&q, 2);
enqueue(&q, 3);
printf("Dequeued: %d\n", dequeue(&q));
enqueue(&q, 4);
printf("Dequeued: %d\n", dequeue(&q));
return 0;
}
push(&q->s1, val); // push new element onto s1
add new element to stack1 to keep insertion order
if (isEmpty(&q->s2)) { while (!isEmpty(&q->s1)) { int x = pop(&q->s1); push(&q->s2, x); } }
transfer all elements from stack1 to stack2 to reverse order when stack2 empty
return pop(&q->s2); // pop from s2 is dequeue
remove and return the oldest element from stack2