0% found this document useful (0 votes)
11 views2 pages

Implementing Stack with Queues in C

Uploaded by

suzukikun583
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views2 pages

Implementing Stack with Queues in C

Uploaded by

suzukikun583
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <stdio.

h>
#include <stdlib.h>

#define MAX_SIZE 100

int queue1[MAX_SIZE], queue2[MAX_SIZE];


int front1 = -1, rear1 = -1;
int front2 = -1, rear2 = -1;

// Function to enqueue an element into queue1


void enqueue1(int data) {
if (rear1 == MAX_SIZE - 1) {
printf("Queue overflow\n");
return;
}
if (front1 == -1) {
front1 = 0;
}
rear1++;
queue1[rear1] = data;
}

// Function to dequeue an element from queue1


int dequeue1() {
if (front1 == -1) {
printf("Queue underflow\n");
return -1;
}
int data = queue1[front1];
front1++;
if (front1 > rear1) {
front1 = rear1 = -1;
}
return data;
}

// Function to implement stack push operation using queues


void stack_push(int data) {
enqueue1(data);
}

// Function to implement stack pop operation using queues


int stack_pop() {
int data;
while (rear1 != 0) {
enqueue2(dequeue1());
}

data = dequeue1();

while (rear2 != -1) {


enqueue1(dequeue2());
}

return data;
}

// Function to display the stack elements


void display() {
if (front1 == -1) {
printf("Stack is empty\n");
return;
}
printf("Stack elements:\n");
while (front1 != -1) {
printf("%d ", queue1[front1]);
enqueue2(dequeue1());
}
while (rear2 != -1) {
enqueue1(dequeue2());
}
printf("\n");
}

int main() {
stack_push(10);
stack_push(20);
stack_push(30);

printf("Popped element: %d\n", stack_pop());

display();

return 0;
}

You might also like