DATA STRUCTURES PROGRAM • QUEUES & DEQUES
Implement a Stack Using Two Queues
Learn how to implement a stack using two queues using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
30 20 10
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void push_value(int first[], int *first_count, int second[], int *second_count, int value)
{
second[(*second_count)++] = value;
for (int index = 0; index < *first_count; index++) second[(*second_count)++] = first[index];
for (int index = 0; index < *second_count; index++) first[index] = second[index];
*first_count = *second_count;
*second_count = 0;
}
int main(void)
{
int first[20], second[20];
int first_count = 0, second_count = 0;
push_value(first, &first_count, second, &second_count, 10);
push_value(first, &first_count, second, &second_count, 20);
push_value(first, &first_count, second, &second_count, 30);
printf("%d %d %d\n", first[0], first[1], first[2]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
30 20 10
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Place each new value before all older queue values so the front behaves as a stack top.
- Display the computed result.
Place each new value before all older queue values so the front behaves as a stack top.
EFFICIENCY
Time and space complexity
Time complexity
O(n) push, O(1) pop
Auxiliary space
O(n)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
