Created
November 4, 2025 12:35
-
-
Save lakshyaraj2006/4b1e71242a2f2f3e6d2bdda278903543 to your computer and use it in GitHub Desktop.
Implement Stack using Queue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include<stdio.h> | |
| #include<stdlib.h> | |
| struct Queue { | |
| int size; | |
| int front; | |
| int rear; | |
| int* arr; | |
| }; | |
| struct Stack { | |
| struct Queue* q1; | |
| struct Queue* q2; | |
| }; | |
| int isEmpty(struct Queue* q) { | |
| return q->front == -1; | |
| } | |
| int isFull(struct Queue* q) { | |
| return q->rear == q->size - 1; | |
| } | |
| void enqueue(struct Queue* q, int val) { | |
| if (isFull(q)) { | |
| printf("Queue Overflow\n"); | |
| return; | |
| } | |
| if (q->front == -1) q->front = 0; | |
| q->rear++; | |
| q->arr[q->rear] = val; | |
| } | |
| int dequeue(struct Queue* q) { | |
| if (isEmpty(q)) { | |
| return -1; | |
| } | |
| int val = q->arr[q->front]; | |
| if (q->front == q->rear) { | |
| q->front = q->rear = -1; | |
| } else { | |
| q->front++; | |
| } | |
| return val; | |
| } | |
| void push(struct Stack* s, int val) { | |
| if (isFull(s->q1)) { | |
| printf("Stack Overflow\n"); | |
| } else { | |
| enqueue(s->q1, val); | |
| } | |
| } | |
| int pop(struct Stack* s) { | |
| int val = -1; | |
| if (isEmpty(s->q1)) { | |
| printf("Stack Underflow\n"); | |
| return -1; | |
| } | |
| s->q2->front = s->q2->rear = -1; | |
| while (s->q1->front != s->q1->rear) { | |
| int temp = dequeue(s->q1); | |
| enqueue(s->q2, temp); | |
| } | |
| val = dequeue(s->q1); | |
| struct Queue* temp = s->q1; | |
| s->q1 = s->q2; | |
| s->q2 = temp; | |
| return val; | |
| } | |
| int main() { | |
| struct Queue *q1 = (struct Queue *)malloc(sizeof(struct Queue)); | |
| struct Queue *q2 = (struct Queue *)malloc(sizeof(struct Queue)); | |
| struct Stack *s = (struct Stack *)malloc(sizeof(struct Stack)); | |
| q1->size = q2->size = 5; | |
| q1->rear = q1->front = q2->rear = q2->front = -1; | |
| q1->arr = (int *)malloc(q1->size * sizeof(int)); | |
| q2->arr = (int *)malloc(q2->size * sizeof(int)); | |
| s->q1 = q1; | |
| s->q2 = q2; | |
| push(s, 50); | |
| push(s, 12); | |
| push(s, 23); | |
| push(s, 5); | |
| push(s, 11); | |
| printf("Popped value: %d\n", pop(s)); | |
| printf("Popped value: %d\n", pop(s)); | |
| printf("Popped value: %d\n", pop(s)); | |
| printf("Popped value: %d\n", pop(s)); | |
| printf("Popped value: %d\n", pop(s)); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment