MIT-Curricular/DS/C/Lab/Week5/QueueStack.c

84 lines
1.4 KiB
C
Raw Permalink Normal View History

2024-09-03 00:26:38 +05:30
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int items[MAX_SIZE];
int top;
} Stack;
Stack* createStack() {
Stack* s = (Stack*)malloc(sizeof(Stack));
s->top = -1;
return s;
}
void push(Stack* s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
s->items[++(s->top)] = x;
}
int pop(Stack* s) {
if (s->top == -1) {
printf("Stack Underflow\n");
return -1;
}
return s->items[(s->top)--];
}
int isEmpty(Stack* s) {
return s->top == -1;
}
typedef struct {
Stack* s1;
Stack* s2;
} Queue;
Queue* createQueue() {
Queue* q = (Queue*)malloc(sizeof(Queue));
q->s1 = createStack();
q->s2 = createStack();
return q;
}
void enqueue(Queue* q, int x) {
push(q->s1, x);
}
int dequeue(Queue* q) {
int x;
if (isEmpty(q->s1) && isEmpty(q->s2)) {
printf("Queue is empty\n");
return -1;
}
if (isEmpty(q->s2)) {
while (!isEmpty(q->s1)) {
x = pop(q->s1);
push(q->s2, x);
}
}
return pop(q->s2);
}
int main() {
Queue* q = createQueue();
enqueue(q, 1);
enqueue(q, 2);
enqueue(q, 3);
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
enqueue(q, 4);
printf("%d\n", dequeue(q));
printf("%d\n", dequeue(q));
return 0;
}