Implement Queue using Stacks in C++

🚀 Day 115 of My DSA Problem Solving Journey - The Grind Continues! 🎉 After diving into custom stacks yesterday, today I explored how to use them to mimic entirely different data structures! I tackled LeetCode's "Implement Queue using Stacks" (Easy) in C++. The Problem: We need to design a custom Queue (which follows First-In-First-Out / FIFO) using strictly standard Stack operations (which follow Last-In-First-Out / LIFO). My Approach: How do you reverse the behavior of a LIFO structure to act like a FIFO one? The secret lies in a classic Two-Stack approach! 🧠 The Logic: Two Stacks: I used an input stack (s1) to collect incoming data, and an output stack (s2) to serve the data out. Push Operation: Whenever a new element arrives, I simply push it onto s1. Super fast and straightforward! Pop & Peek Operations: Here is where the magic happens! To get the front of the queue, we actually need the bottom element of s1. So, whenever s2 is empty, I run a while loop to pop everything out of s1 and push it straight into s2. This completely reverses the order! Now, the top of s2 perfectly represents the front of our queue. Empty: The queue is fully empty only when both s1 and s2 have zero elements. Takeaway: This problem is a brilliant lesson in Amortized Time Complexity. Moving elements from one stack to another takes O(N) time, but because we only do this heavy lifting when s2 is completely empty, the average time complexity across multiple pop or peek calls effectively drops to O(1). A clever trick to move elements only when absolutely necessary! ⚡ Keep pushing! 💻🔥 #Day115 #CPP #Stack #Queue #LeetCode #DataStructures #Algorithms #DSA #ProblemSolving #CodingJourney #ContinuousLearning #REGexSoftwareServices REGex Software Services LeetCode

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories