Bird
0
0
DSA Cprogramming~30 mins

Queue Using Two Stacks in DSA C - Build from Scratch

Choose your learning style9 modes available
Queue Using Two Stacks
📖 Scenario: Imagine you are managing a line of customers waiting for service. You want to keep track of who comes first and who leaves first, just like a queue. But you only have two stacks (like two piles of plates) to help you. Your task is to build a queue using these two stacks.
🎯 Goal: Build a queue using two stacks in C. You will create two stacks, add elements to the queue, remove elements from the queue, and finally print the queue's state.
📋 What You'll Learn
Create two stacks using arrays and integer variables for top positions.
Create a function to enqueue (add) elements to the queue using the first stack.
Create a function to dequeue (remove) elements from the queue using both stacks.
Print the queue elements in order after all operations.
💡 Why This Matters
🌍 Real World
Queues are used in many real-life situations like customer service lines, printer job management, and task scheduling. Using two stacks to build a queue helps understand how data structures can work together.
💼 Career
Understanding how to implement one data structure using others is a common interview question and helps improve problem-solving skills for software development roles.
Progress0 / 4 steps
1
Create Two Stacks
Create two integer arrays called stack1 and stack2 each with size 5. Also create two integer variables called top1 and top2 and set both to -1.
DSA C
Hint

Think of top1 and top2 as the positions of the top plates in each stack. Starting at -1 means the stacks are empty.

2
Create Enqueue Function
Write a function called enqueue that takes an integer value. Inside, increase top1 by 1 and add value to stack1[top1].
DSA C
Hint

Adding to the queue means pushing onto stack1. Increase top1 first, then put the value on top.

3
Create Dequeue Function
Write a function called dequeue that returns an integer. If top2 is -1, move all elements from stack1 to stack2 by popping from stack1 and pushing to stack2. Then pop and return the top element from stack2.
DSA C
Hint

To remove from the queue, if stack2 is empty, move all items from stack1 to stack2 to reverse their order. Then pop from stack2.

4
Print Queue Elements
Write code to enqueue the values 10, 20, and 30. Then dequeue one element. Finally, print the remaining elements in the queue in order by dequeuing until empty. Use printf to print each element followed by a space.
DSA C
Hint

After removing one element, the queue should have 20 and 30 left. Print them separated by spaces.