Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on Stack
  • Practice Stack
  • MCQs on Stack
  • Stack Tutorial
  • Stack Operations
  • Stack Implementations
  • Monotonic Stack
  • Infix to Postfix
  • Prefix to Postfix
  • Prefix to Infix
  • Advantages & Disadvantages
Open In App
Next Article:
Clone a stack without extra space
Next article icon

Clone a stack without extra space

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

Given a source stack, copy the contents of the source stack to the destination stack maintaining the same order without using extra space.

Examples: 

Input: st = [ 3, 2, 1 ]
Output: Clone : [3, 2, 1]

Input: st = [10, 5, 4]
Output: Clone = [10, 5, 4]

Reverse The Stack - O(n ^ 2) Time and O(1) Space

The idea is to reverse the given stack using cloned stack as auxiliary. To reverse the stack, we mainly one by one move the top of the given stack to the bottom.

[1, 2. 3. 4] => [4, 1, 2, 3] => [4, 3, 1, 2] => [4, 3, 2, 1]

After this step, our task is simple, we only need to move the items one by one to clone and our clone becomes [1, 2, 3, 4]

C++
#include <bits/stdc++.h> using namespace std;  void clonedStack(stack<int> &st, stack<int> &cloned) {      int count = 0;      // reverse the order of the values in source stack     while(count != st.size() - 1) {         int topVal = st.top();         st.pop();         while(count != st.size()) {             cloned.push(st.top());             st.pop();         }         st.push(topVal);         while(cloned.size() != 0) {             st.push(cloned.top());             cloned.pop();         }         count += 1;     }      // pop the values from source and     // push into destination stack     while(st.size() != 0) {         cloned.push(st.top());         st.pop();     } }  int main() {     stack<int> source, dest;     source.push(1);     source.push(2);     source.push(3);      cout << "Source Stack:" << endl;     stack<int> temp = source;     while(!temp.empty()) {         cout << temp.top() << " ";         temp.pop();     }     cout << endl;      clonedStack(source, dest);      cout << "Destination Stack:" << endl;     while(!dest.empty()) {         cout << dest.top() << " ";         dest.pop();     }      return 0; } 
Java
import java.util.*;  class GfG {      static void clonedStack(Stack<Integer> st, Stack<Integer> cloned) {          int count = 0;          // reverse the order of the values in source stack         while(count != st.size() - 1) {             int topVal = st.peek();             st.pop();             while(count != st.size()) {                 cloned.push(st.peek());                 st.pop();             }             st.push(topVal);             while(cloned.size() != 0) {                 st.push(cloned.peek());                 cloned.pop();             }             count += 1;         }          // pop the values from source and         // push into destination stack         while(st.size() != 0) {             cloned.push(st.peek());             st.pop();         }     }      public static void main(String[] args) {         Stack<Integer> source = new Stack<>();         Stack<Integer> dest = new Stack<>();         source.push(1);         source.push(2);         source.push(3);          System.out.println("Source Stack:");         Stack<Integer> temp = (Stack<Integer>) source.clone();         while(!temp.empty()) {             System.out.print(temp.peek() + " ");             temp.pop();         }         System.out.println();          clonedStack(source, dest);          System.out.println("Destination Stack:");         while(!dest.empty()) {             System.out.print(dest.peek() + " ");             dest.pop();         }     } } 
Python
def clonedStack(st, cloned):      count = 0      # reverse the order of the values in source stack     while count != len(st) - 1:         topVal = st[-1]         st.pop()         while count != len(st):             cloned.append(st[-1])             st.pop()         st.append(topVal)         while len(cloned) != 0:             st.append(cloned[-1])             cloned.pop()         count += 1      # pop the values from source and     # push into destination stack     while len(st) != 0:         cloned.append(st[-1])         st.pop()   source = [] dest = [] source.append(1) source.append(2) source.append(3)  print("Source Stack:") temp = source[:] while temp:     print(temp[-1], end=" ")     temp.pop() print()  clonedStack(source, dest)  print("Destination Stack:") while dest:     print(dest[-1], end=" ")     dest.pop() 
C#
using System; using System.Collections.Generic;  class GfG {      static void clonedStack(Stack<int> st, Stack<int> cloned) {          int count = 0;          // reverse the order of the values in source stack         while(count != st.Count - 1) {             int topVal = st.Peek();             st.Pop();             while(count != st.Count) {                 cloned.Push(st.Peek());                 st.Pop();             }             st.Push(topVal);             while(cloned.Count != 0) {                 st.Push(cloned.Peek());                 cloned.Pop();             }             count += 1;         }          // pop the values from source and         // push into destination stack         while(st.Count != 0) {             cloned.Push(st.Peek());             st.Pop();         }     }      static void Main() {         Stack<int> source = new Stack<int>();         Stack<int> dest = new Stack<int>();         source.Push(1);         source.Push(2);         source.Push(3);          Console.WriteLine("Source Stack:");         Stack<int> temp = new Stack<int>(new Stack<int>(source));         while(temp.Count != 0) {             Console.Write(temp.Peek() + " ");             temp.Pop();         }         Console.WriteLine();          clonedStack(source, dest);          Console.WriteLine("Destination Stack:");         while(dest.Count != 0) {             Console.Write(dest.Peek() + " ");             dest.Pop();         }     } } 
JavaScript
function clonedStack(st, cloned) {      let count = 0;      // reverse the order of the values in source stack     while(count !== st.length - 1) {         let topVal = st[st.length - 1];         st.pop();         while(count !== st.length) {             cloned.push(st[st.length - 1]);             st.pop();         }         st.push(topVal);         while(cloned.length !== 0) {             st.push(cloned[cloned.length - 1]);             cloned.pop();         }         count += 1;     }      // pop the values from source and     // push into destination stack     while(st.length !== 0) {         cloned.push(st[st.length - 1]);         st.pop();     } }  let source = []; let dest = []; source.push(1); source.push(2); source.push(3);  console.log("Source Stack:"); let temp = [...source]; while(temp.length) {     console.log(temp[temp.length - 1] + " ");     temp.pop(); }  clonedStack(source, dest);  console.log("Destination Stack:"); while(dest.length) {     console.log(dest[dest.length - 1] + " ");     dest.pop(); } 

Output
Source Stack: 3 2 1  Destination Stack: 3 2 1 

Using Recursion - O(n) Time and O(n) Space for Recursion Call Stack

The idea is to use recursion to reverse the source stack and then build the cloned stack as we return from the recursive calls. This eliminates the need for explicit iteration or auxiliary data structures to track the order. We recursively pop each element from the source stack until it becomes empty. Then, as the recursive calls unwind, we push those elements into the cloned stack in the original bottom-to-top order, effectively cloning the stack.

Follow the below given steps:

  • Pass two stack references: one for the original stack and another for the cloned stack.
  • If the original stack is empty, return (base case for recursion).
  • Pop the top element from the original stack and store it in a temporary variable.
  • Make a recursive call with the modified original stack and the cloned stack.
  • After the recursive call returns, push the temporarily stored element into the cloned stack.

Below is given the implementation:

C++
#include <bits/stdc++.h> using namespace std;  void clonedStack(stack<int> &st, stack<int> &cloned) {      // If the source stack is empty, return.     if (st.empty())         return;      // Pop an element from the source stack.     int temp = st.top();     st.pop();      // Recursively clone the remaining elements.     clonedStack(st, cloned);      // Push the popped element to the cloned stack.     cloned.push(temp); }  int main() {     stack<int> source, dest;     source.push(1);     source.push(2);     source.push(3);      cout << "Source Stack:" << endl;     stack<int> temp = source;     while(!temp.empty()) {         cout << temp.top() << " ";         temp.pop();     }     cout << endl;      clonedStack(source, dest);      cout << "Destination Stack:" << endl;     while(!dest.empty()) {         cout << dest.top() << " ";         dest.pop();     }      return 0; } 
Java
import java.util.*;  class GfG {      static void clonedStack(Stack<Integer> st, Stack<Integer> cloned) {          // If the source stack is empty, return.         if (st.empty())             return;          // Pop an element from the source stack.         int temp = st.peek();         st.pop();          // Recursively clone the remaining elements.         clonedStack(st, cloned);          // Push the popped element to the cloned stack.         cloned.push(temp);     }      public static void main(String[] args) {         Stack<Integer> source = new Stack<>();         Stack<Integer> dest = new Stack<>();         source.push(1);         source.push(2);         source.push(3);          System.out.println("Source Stack:");         Stack<Integer> temp = (Stack<Integer>) source.clone();         while(!temp.empty()) {             System.out.print(temp.peek() + " ");             temp.pop();         }         System.out.println();          clonedStack(source, dest);          System.out.println("Destination Stack:");         while(!dest.empty()) {             System.out.print(dest.peek() + " ");             dest.pop();         }     } } 
Python
def clonedStack(st, cloned):      # If the source stack is empty, return.     if not st:         return      # Pop an element from the source stack.     temp = st[-1]     st.pop()      # Recursively clone the remaining elements.     clonedStack(st, cloned)      # Push the popped element to the cloned stack.     cloned.append(temp)   source = [] dest = [] source.append(1) source.append(2) source.append(3)  print("Source Stack:") temp = source.copy() while temp:     print(temp[-1], end=" ")     temp.pop() print()  clonedStack(source, dest)  print("Destination Stack:") while dest:     print(dest[-1], end=" ")     dest.pop() 
C#
using System; using System.Collections.Generic;  class GfG {      static void clonedStack(Stack<int> st, Stack<int> cloned) {          // If the source stack is empty, return.         if (st.Count == 0)             return;          // Pop an element from the source stack.         int temp = st.Peek();         st.Pop();          // Recursively clone the remaining elements.         clonedStack(st, cloned);          // Push the popped element to the cloned stack.         cloned.Push(temp);     }      static void Main() {         Stack<int> source = new Stack<int>();         Stack<int> dest = new Stack<int>();         source.Push(1);         source.Push(2);         source.Push(3);          Console.WriteLine("Source Stack:");         Stack<int> temp = new Stack<int>(new Stack<int>(source));         while(temp.Count > 0) {             Console.Write(temp.Peek() + " ");             temp.Pop();         }         Console.WriteLine();          clonedStack(source, dest);          Console.WriteLine("Destination Stack:");         while(dest.Count > 0) {             Console.Write(dest.Peek() + " ");             dest.Pop();         }     } } 
JavaScript
function clonedStack(st, cloned) {      // If the source stack is empty, return.     if (st.length === 0)         return;      // Pop an element from the source stack.     let temp = st[st.length - 1];     st.pop();      // Recursively clone the remaining elements.     clonedStack(st, cloned);      // Push the popped element to the cloned stack.     cloned.push(temp); }  let source = []; let dest = []; source.push(1); source.push(2); source.push(3);  console.log("Source Stack:"); let temp = [...source]; while (temp.length !== 0) {     console.log(temp[temp.length - 1] + " ");     temp.pop(); }  clonedStack(source, dest);  console.log("Destination Stack:"); while (dest.length !== 0) {     console.log(dest[dest.length - 1] + " ");     dest.pop(); } 

Output
Source Stack: 3 2 1  Destination Stack: 3 2 1 

Note: This solution does not use any explicit space but requires function call stack space to manage recursion.


Next Article
Clone a stack without extra space

R

rituraj_jain
Improve
Article Tags :
  • Linked List
  • Stack
  • Technical Scripter
  • DSA
  • Technical Scripter 2018
  • Reverse
Practice Tags :
  • Linked List
  • Reverse
  • Stack

Similar Reads

    Clone a stack without using extra space | Set 2
    Given a stack S, the task is to copy the content of the given stack S to another stack T maintaining the same order.Examples:Input: Source:- |5| |4| |3| |2| |1|Output: Destination:- |5| |4| |3| |2| |1|Input: Source:- |12| |13| |14| |15| |16|Output: Destination:- |12| |13| |14| |15| |16|Reversing the
    7 min read
    Reverse a stack without using extra space in O(n)
    Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed. Examples: Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6 We have discussed a way of reversing a stack in the below post.Reverse a Stack using Recu
    6 min read
    Check if the two given stacks are same
    Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: Approach: Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or
    6 min read
    How to Reverse a Stack using Recursion
    Write a program to reverse a stack using recursion, without using any loop.Example: Input: elements present in stack from top to bottom 4 3 2 1Output: 1 2 3 4Input: elements present in stack from top to bottom 1 2 3Output: 3 2 1The idea of the solution is to hold all values in Function Call Stack un
    4 min read
    Reversing a Stack using two empty Stacks
    Given a stack S, the task is to reverse the stack S using two additional stacks. Example: Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1→top2345After reversing it, use two additional stacks:5→top4321 Input: S={1, 25, 17}Output: 17 25 1 Approach: Follow the steps below to
    6 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