Practical 2 ( A ). Queue using Stack - SCIENCE BUZZ

Practical 2 ( A ). Queue using Stack

#include<stdio.h>
#define m 100

int s1[m], s2[m];
int top1 = -1, top2 = -1;
int count = 0;

void push1(int x) {
    if (top1 == m - 1) {
        printf("Overflow\n");
    } else {
        s1[++top1] = x;
    }
}

void push2(int x) {
    if (top2 == m - 1) {
        printf("Overflow\n");
    } else {
        s2[++top2] = x;
    }
}

int pop1() {
    if (top1 == -1) {
        printf("Underflow\n");
        return -1;
    }
    return s1[top1--];
}

int pop2() {
    if (top2 == -1) {
        printf("Underflow\n");
        return -1;
    }
    return s2[top2--];
}

void enqueue(int x) {
    push1(x);
    count++;
}

void dequeue() {
    if (top1 == -1 && top2 == -1) {
        printf("Underflow\n");
        return;
    }
    if (top2 == -1) { // Transfer elements only if s2 is empty
        while (top1 != -1) {
            push2(pop1());
        }
    }
    int dequeuedElement = pop2();
    if (dequeuedElement != -1) {
        printf("Dequeued: %d\n", dequeuedElement);
        count--;
    }
}

void display() {
    if (top1 == -1 && top2 == -1) {
        printf("Queue is empty\n");
        return;
    }

    printf("Queue: ");
    for (int i = top2; i >= 0; i--) { // Display elements in s2 (in reverse)
        printf("%d\t", s2[i]);
    }
    for (int i = 0; i <= top1; i++) { // Display elements in s1
        printf("%d\t", s1[i]);
    }
    printf("\n");
}

int main() {
    enqueue(5);
    enqueue(2);
    enqueue(1);
    display();
    dequeue();
    dequeue();
    enqueue(4);
    enqueue(17);
    display();
    return 0;
}
Practical 2 ( A ). Queue using Stack Practical 2 ( A ). Queue using Stack Reviewed by RISHI and ARYAN on 21:17 Rating: 5

No comments:

May I help you ?

Powered by Blogger.