Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++
  • Standard Template Library
  • STL Vector
  • STL List
  • STL Set
  • STL Map
  • STL Stack
  • STL Queue
  • STL Priority Queue
  • STL Interview Questions
  • STL Cheatsheet
  • C++ Templates
  • C++ Functors
  • C++ Iterators
Open In App
Next Article:
C++ Program to Reverse a String Using Stack
Next article icon

Queue using Stacks

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.

Stack and Queue with insert and delete operations

Table of Content

  • By Making Enqueue Operation Costly
  • By Making Dequeue Operation Costly
  • Queue Implementation Using One Stack and Recursion

By Making Enqueue Operation Costly

A queue can be implemented using two stacks. Let the queue be represented as q, and the stacks used for its implementation be s1 and s2.

In this approach, the enqueue operation is made costly by transferring elements from stack1 to stack2 before adding the new element. This ensures that the elements in stack2 are in the correct order for dequeuing. The dequeue operation remains efficient, as it simply involves popping elements from stack2.

enqueue(q, x): 

  • While stack1 is not empty, push everything from stack1 to stack2.
  • Push x to stack1 (assuming size of stacks is unlimited).
  • Push everything back to stack1.

dequeue(q): 

  • If stack1 is empty then error.
  • Pop an item from stack1 and return it.

Below is given the implementation:

C++
#include <bits/stdc++.h> using namespace std;  struct Queue {     stack<int> s1, s2;      void enqueue(int x) {          // Move all elements from s1 to s2         while (!s1.empty()) {             s2.push(s1.top());             s1.pop();         }          // Push item into s1         s1.push(x);          // Push everything back to s1         while (!s2.empty()) {             s1.push(s2.top());             s2.pop();         }     }      // Dequeue an item from the queue     int dequeue() {          // if first stack is empty         if (s1.empty()) {             return -1;         }          // Return top of s1         int x = s1.top();         s1.pop();         return x;     } };  // Driver code int main() {     Queue q;     q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      cout << q.dequeue() << '\n';     cout << q.dequeue() << '\n';     cout << q.dequeue() << '\n';      return 0; } 
Java
import java.util.*;  public class GfG {      static class Queue {         Stack<Integer> s1 = new Stack<>();         Stack<Integer> s2 = new Stack<>();          void enqueue(int x) {              // Move all elements from s1 to s2             while (!s1.empty()) {                 s2.push(s1.peek());                 s1.pop();             }              // Push item into s1             s1.push(x);              // Push everything back to s1             while (!s2.empty()) {                 s1.push(s2.peek());                 s2.pop();             }         }          // Dequeue an item from the queue         int dequeue() {              // if first stack is empty             if (s1.empty()) {                 return -1;             }              // Return top of s1             int x = s1.peek();             s1.pop();             return x;         }     }      public static void main(String[] args) {         Queue q = new Queue();         q.enqueue(1);         q.enqueue(2);         q.enqueue(3);          System.out.println(q.dequeue());         System.out.println(q.dequeue());         System.out.println(q.dequeue());     } } 
Python
class Queue:     def __init__(self):         self.s1 = []         self.s2 = []      def enqueue(self, x):          # Move all elements from s1 to s2         while self.s1:             self.s2.append(self.s1.pop())          # Push item into s1         self.s1.append(x)          # Push everything back to s1         while self.s2:             self.s1.append(self.s2.pop())      # Dequeue an item from the queue     def dequeue(self):          # if first stack is empty         if not self.s1:             return -1          # Return top of s1         x = self.s1.pop()         return x  if __name__ == "__main__":     q = Queue()     q.enqueue(1)     q.enqueue(2)     q.enqueue(3)      print(q.dequeue())     print(q.dequeue())     print(q.dequeue()) 
C#
using System; using System.Collections.Generic;  public class GfG {      public class Queue {         Stack<int> s1 = new Stack<int>();         Stack<int> s2 = new Stack<int>();          public void Enqueue(int x) {              // Move all elements from s1 to s2             while (s1.Count > 0) {                 s2.Push(s1.Peek());                 s1.Pop();             }              // Push item into s1             s1.Push(x);              // Push everything back to s1             while (s2.Count > 0) {                 s1.Push(s2.Peek());                 s2.Pop();             }         }          // Dequeue an item from the queue         public int Dequeue() {              // if first stack is empty             if (s1.Count == 0) {                 return -1;             }              // Return top of s1             int x = s1.Peek();             s1.Pop();             return x;         }     }      public static void Main(string[] args) {         Queue q = new Queue();         q.Enqueue(1);         q.Enqueue(2);         q.Enqueue(3);          Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());     } } 
JavaScript
//  class Queue {     constructor() {         this.s1 = [];         this.s2 = [];     }      enqueue(x) {          // Move all elements from s1 to s2         while (this.s1.length) {             this.s2.push(this.s1.pop());         }          // Push item into s1         this.s1.push(x);          // Push everything back to s1         while (this.s2.length) {             this.s1.push(this.s2.pop());         }     }      // Dequeue an item from the queue     dequeue() {          // if first stack is empty         if (this.s1.length === 0) {             return -1;         }          // Return top of s1         let x = this.s1.pop();         return x;     } }  function main() {     let q = new Queue();     q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      console.log(q.dequeue());     console.log(q.dequeue());     console.log(q.dequeue()); }  main(); 

Output
1 2 3 

Time Complexity: O(n), for push operation, and O(1) for pop operation.
Auxiliary Space: O(n). 

By Making Dequeue Operation Costly

In this approach, the new element is pushed onto the top of stack1 during the enqueue operation. For the dequeue operation, if stack2 is empty, all elements are transferred from stack1 to stack2, and the element at the top of stack2 is returned.

enqueue(q, x):

  • Push x to stack1 (assuming size of stacks is unlimited).

dequeue(q):

  • If both stacks are empty then error.
  • If stack2 is empty
    • While stack1 is not empty, push everything from stack1 to stack2.
  • Pop the element from stack2 and return it.

Below is given the implementation:

C++
#include <bits/stdc++.h> using namespace std;  struct Queue {     stack<int> s1, s2;      // Enqueue an item to the queue     void enqueue(int x) {          // Push item into the first stack         s1.push(x);     }      // Dequeue an item from the queue     int dequeue() {          // if both stacks are empty         if (s1.empty() && s2.empty()) {             return -1;         }          // if s2 is empty, move         // elements from s1         if (s2.empty()) {             while (!s1.empty()) {                 s2.push(s1.top());                 s1.pop();             }         }          // return the top item from s2         int x = s2.top();         s2.pop();         return x;     } };  int main() {     Queue q;      q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      cout << q.dequeue() << '\n';      cout << q.dequeue() << '\n';      cout << q.dequeue() << '\n';       return 0; } 
Java
import java.util.*;  public class GfG {      static class Queue {         Stack<Integer> s1 = new Stack<>();         Stack<Integer> s2 = new Stack<>();          // Enqueue an item to the queue         void enqueue(int x) {              // Push item into the first stack             s1.push(x);         }          // Dequeue an item from the queue         int dequeue() {              // if both stacks are empty             if (s1.empty() && s2.empty()) {                 return -1;             }              // if s2 is empty, move             // elements from s1             if (s2.empty()) {                 while (!s1.empty()) {                     s2.push(s1.peek());                     s1.pop();                 }             }              // return the top item from s2             int x = s2.peek();             s2.pop();             return x;         }     }      public static void main(String[] args) {         Queue q = new Queue();          q.enqueue(1);         q.enqueue(2);         q.enqueue(3);          System.out.println(q.dequeue());         System.out.println(q.dequeue());         System.out.println(q.dequeue());     } } 
Python
class Queue:     def __init__(self):         self.s1 = []         self.s2 = []      # Enqueue an item to the queue     def enqueue(self, x):          # Push item into the first stack         self.s1.append(x)      # Dequeue an item from the queue     def dequeue(self):          # if both stacks are empty         if not self.s1 and not self.s2:             return -1          # if s2 is empty, move         # elements from s1         if not self.s2:             while self.s1:                 self.s2.append(self.s1.pop())          # return the top item from s2         x = self.s2.pop()         return x  if __name__ == "__main__":     q = Queue()      q.enqueue(1)     q.enqueue(2)     q.enqueue(3)      print(q.dequeue())     print(q.dequeue())     print(q.dequeue()) 
C#
using System; using System.Collections.Generic;  public class GfG {      public class Queue {         Stack<int> s1 = new Stack<int>();         Stack<int> s2 = new Stack<int>();          // Enqueue an item to the queue         public void Enqueue(int x) {              // Push item into the first stack             s1.Push(x);         }          // Dequeue an item from the queue         public int Dequeue() {              // if both stacks are empty             if (s1.Count == 0 && s2.Count == 0) {                 return -1;             }              // if s2 is empty, move             // elements from s1             if (s2.Count == 0) {                 while (s1.Count > 0) {                     s2.Push(s1.Peek());                     s1.Pop();                 }             }              // return the top item from s2             int x = s2.Peek();             s2.Pop();             return x;         }     }      public static void Main(string[] args) {         Queue q = new Queue();          q.Enqueue(1);         q.Enqueue(2);         q.Enqueue(3);          Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());     } } 
JavaScript
//  class Queue {     constructor() {         this.s1 = [];         this.s2 = [];     }      // Enqueue an item to the queue     enqueue(x) {          // Push item into the first stack         this.s1.push(x);     }      // Dequeue an item from the queue     dequeue() {          // if both stacks are empty         if (this.s1.length === 0 && this.s2.length === 0) {             return -1;         }          // if s2 is empty, move         // elements from s1         if (this.s2.length === 0) {             while (this.s1.length) {                 this.s2.push(this.s1.pop());             }         }          // return the top item from s2         let x = this.s2.pop();         return x;     } }  function main() {     let q = new Queue();      q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      console.log(q.dequeue());     console.log(q.dequeue());     console.log(q.dequeue()); }  main(); 

Output
1 2 3 

Time Complexity: O(n), for pop operation, and O(1) for push operation. This approach is definitely more efficient than first approach. In the first approach, all elements are moved twice during the enqueue operation, which is less efficient. However, in this approach, elements are only moved once during the dequeue operation, and only if stack2 is empty. This leads to an amortized time complexity of the dequeue operation being Θ(1).
Space Complexity: O(n)

Queue Implementation Using One Stack and Recursion

A queue can also be implemented using a single user-defined stack and recursion (via the function call stack).

enqueue(x)

  • Push the element x onto stack1.

dequeue()

  • If stack1 is empty, return an error.
  • If stack1 has only one element, return it.
  • Otherwise, recursively pop all elements from stack1, store the popped element in a variable res, then push res back into stack1 and return res.

Step 3 ensures that the last popped element is always returned. Since the recursion halts when there is only one item left in stack1 (as described in step 2), the last element of stack1 is returned by the dequeue() function, with all other elements being pushed back into stack1 in the process.

Below is given the implementation:

C++
#include <bits/stdc++.h> using namespace std;  struct Queue {     stack<int> s;      // Enqueue an item to the queue     void enqueue(int x) {         s.push(x);     }      // Dequeue an item from the queue     int dequeue() {         if (s.empty()) {             return -1;         }          // pop an item from the stack         int x = s.top();         s.pop();          // if stack becomes empty, return         // the popped item         if (s.empty())             return x;          // recursive call         int item = dequeue();          // push popped item back to the stack         s.push(x);          // return the result of dequeue() call         return item;     } };  int main() {     Queue q;     q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      cout << q.dequeue() << '\n';     cout << q.dequeue() << '\n';     cout << q.dequeue() << '\n';      return 0; } 
Java
import java.util.*;  public class GfG {      static class Queue {         Stack<Integer> s = new Stack<>();          // Enqueue an item to the queue         void enqueue(int x) {             s.push(x);         }          // Dequeue an item from the queue         int dequeue() {             if (s.empty()) {                 return -1;             }              // pop an item from the stack             int x = s.peek();             s.pop();              // if stack becomes empty, return             // the popped item             if (s.empty())                 return x;              // recursive call             int item = dequeue();              // push popped item back to the stack             s.push(x);              // return the result of dequeue() call             return item;         }     }      public static void main(String[] args) {         Queue q = new Queue();         q.enqueue(1);         q.enqueue(2);         q.enqueue(3);          System.out.println(q.dequeue());         System.out.println(q.dequeue());         System.out.println(q.dequeue());     } } 
Python
#  class Queue:     def __init__(self):         self.s = []      # Enqueue an item to the queue     def enqueue(self, x):         self.s.append(x)      # Dequeue an item from the queue     def dequeue(self):         if not self.s:             return -1          # pop an item from the stack         x = self.s[-1]         self.s.pop()          # if stack becomes empty, return         # the popped item         if not self.s:             return x          # recursive call         item = self.dequeue()          # push popped item back to the stack         self.s.append(x)          # return the result of dequeue() call         return item  if __name__ == "__main__":     q = Queue()     q.enqueue(1)     q.enqueue(2)     q.enqueue(3)      print(q.dequeue())     print(q.dequeue())     print(q.dequeue()) 
C#
using System; using System.Collections.Generic;  public class GfG {      public class Queue {         Stack<int> s = new Stack<int>();          // Enqueue an item to the queue         public void Enqueue(int x) {             s.Push(x);         }          // Dequeue an item from the queue         public int Dequeue() {             if (s.Count == 0) {                 return -1;             }              // pop an item from the stack             int x = s.Peek();             s.Pop();              // if stack becomes empty, return             // the popped item             if (s.Count == 0)                 return x;              // recursive call             int item = Dequeue();              // push popped item back to the stack             s.Push(x);              // return the result of dequeue() call             return item;         }     }      public static void Main(string[] args) {         Queue q = new Queue();         q.Enqueue(1);         q.Enqueue(2);         q.Enqueue(3);          Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());         Console.WriteLine(q.Dequeue());     } } 
JavaScript
//  class Queue {     constructor() {         this.s = [];     }      // Enqueue an item to the queue     enqueue(x) {         this.s.push(x);     }      // Dequeue an item from the queue     dequeue() {         if (this.s.length === 0) {             return -1;         }          // pop an item from the stack         let x = this.s[this.s.length - 1];         this.s.pop();          // if stack becomes empty, return         // the popped item         if (this.s.length === 0)             return x;          // recursive call         let item = this.dequeue();          // push popped item back to the stack         this.s.push(x);          // return the result of dequeue() call         return item;     } }  function main() {     let q = new Queue();     q.enqueue(1);     q.enqueue(2);     q.enqueue(3);      console.log(q.dequeue());     console.log(q.dequeue());     console.log(q.dequeue()); }  main(); 

Output
1 2 3 

Time Complexity: O(n), for push operation, and O(1) for pop operation. The difference from above method is that in this method element is returned and all elements are restored back in a single call.
Auxiliary Space: O(n)



Next Article
C++ Program to Reverse a String Using Stack
author
kartik
Improve
Article Tags :
  • DSA
  • Queue
  • Stack
  • Accolite
  • Adobe
  • Amazon
  • D-E-Shaw
  • Flipkart
  • Goldman Sachs
  • InfoEdge
  • InMobi
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Oracle
  • STL
  • Walmart
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • D-E-Shaw
  • Flipkart
  • Goldman Sachs
  • InfoEdge
  • InMobi
  • MakeMyTrip
  • MAQ Software
  • Microsoft
  • Morgan Stanley
  • Oracle
  • Walmart
  • Queue
  • Stack
  • STL

Similar Reads

  • Stack in C++ STL
    In C++, stack container follows LIFO (Last In First Out) order of insertion and deletion. It means that most recently inserted element is removed first and the first inserted element will be removed last. This is done by inserting and deleting elements at only one end of the stack which is generally
    5 min read
  • stack empty() and stack size() in C++ STL
    The std::stack::size() and std::stack::empty() in C++ are built-in functions that are used to provide information about the size of the stack. They are the member functions of the std::stack container defined inside <stack> header file. stack::empty()The stack::empty() method is used to check
    2 min read
  • stack::push() and stack::pop() in C++ STL
    The stack::push() and stack::pop() method in stack container is used to insert and delete the element from the top of stack. They are the member functions of std::stack container defined inside <stack> header file. In this article, we will learn how to use stack::push() and stack::pop() method
    2 min read
  • stack top() in C++ STL
    In C++, the std::stack::top() is used to find the top element of the std::stack container. It is a member function of std::stack class defined inside the <stack> header file. In this article, we will learn how to find the top element of stack using stack::top() in C++. Example: [GFGTABS] C++ #
    2 min read
  • stack emplace() in C++ STL
    Stacks are a type of container adaptors with LIFO(Last In First Out) type of working, where a new element is added at one end (top) and an element is removed from that end only. stack::emplace() This function is used to insert a new element into the stack container, the new element is added on top o
    3 min read
  • stack swap() in C++ STL
    Stacks are a type of container adaptors with LIFO(Last In First Out) type of work, where a new element is added at one end and (top) an element is removed from that end only. stack::swap()This function is used to swap the contents of one stack with another stack of same type but the size may vary. S
    2 min read
  • List of Stacks in C++ STL
    Prerequisite: List, Stack Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Syntax: list <Type> name_of_list; Stack are a type of container adaptor wit
    3 min read
  • Implementing Stack Using Class Templates in C++
    The task is to implement some important functions of stack like pop(), push(), display(), topElement(), isEmpty(), isFull() using class template in C++. Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or
    5 min read
  • How to implement a Stack using list in C++ STL
    In this article, we will discuss how to implement a Stack using list in C++ STL. Stack is a linear data structure which follows. LIFO(Last In First Out) or FILO(First In Last Out). It mainly supports 4 major operations:1. Push: Push an element into the stack.2. Pop: Removes the element by following
    3 min read
  • Queue using Stacks
    Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations. Table of Content By Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Makin
    11 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences