Skip to content

Instantly share code, notes, and snippets.

@lakshyaraj2006
Created November 4, 2025 12:34
Show Gist options
  • Select an option

  • Save lakshyaraj2006/4cc8eb1a6a68893b100917e6af4a40f0 to your computer and use it in GitHub Desktop.

Select an option

Save lakshyaraj2006/4cc8eb1a6a68893b100917e6af4a40f0 to your computer and use it in GitHub Desktop.
Implement Queue using Stack
#include<stdio.h>
#include<stdlib.h>
struct Stack {
int size;
int top;
int *arr;
};
struct Queue {
struct Stack* s1;
struct Stack* s2;
};
int isEmpty(struct Stack *s) {
if (s->top == -1) {
return 1;
} else {
return 0;
}
}
int isFull(struct Stack *s) {
if (s->top == s->size-1) {
return 1;
} else {
return 0;
}
}
void push(struct Stack *s, int val) {
if (!isFull(s)) {
s->top++;
s->arr[s->top] = val;
}
}
int pop(struct Stack *s) {
int val = -1;
if (!isEmpty(s)) {
val = s->arr[s->top];
s->top--;
}
return val;
}
int top(struct Stack *s) {
int val = -1;
if (!isEmpty(s)) {
val = s->arr[s->top];
}
return val;
}
void enqueue(struct Queue *q, int val) {
if (isFull(q->s1)) {
printf("Queue underflow\n");
} else {
push(q->s1, val);
}
}
int dequeue(struct Queue *q) {
int val = -1;
if (!isEmpty(q->s1)) {
while (!(isEmpty(q->s1)))
{
int temp = top(q->s1);
push(q->s2, temp);
pop(q->s1);
}
val = pop(q->s2);
while (!(isEmpty(q->s2)))
{
int temp = top(q->s2);
push(q->s1, temp);
pop(q->s2);
}
}
return val;
}
int main() {
struct Stack *s1 = (struct Stack *)malloc(sizeof(struct Stack));
struct Stack *s2 = (struct Stack *)malloc(sizeof(struct Stack));
struct Queue *q = (struct Queue *)malloc(sizeof(struct Queue));
s1->size = s2->size = 5;
s1->top = s2->top = -1;
s1->arr = (int *)malloc(s1->size * sizeof(int));
s2->arr = (int *)malloc(s2->size * sizeof(int));
q->s1 = s1;
q->s2 = s2;
enqueue(q, 50);
enqueue(q, 12);
enqueue(q, 23);
enqueue(q, 5);
enqueue(q, 11);
printf("Deuqueued value: %d\n", dequeue(q));
printf("Deuqueued value: %d\n", dequeue(q));
printf("Deuqueued value: %d\n", dequeue(q));
printf("Deuqueued value: %d\n", dequeue(q));
printf("Deuqueued value: %d\n", dequeue(q));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment