Sunday, January 12, 2025
Google search engine
HomeData Modelling & AIClone a stack without using extra space | Set 2

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 Stack-Based Approach: Please refer to the previous post of this article for reversing the stack-based approach.

Time Complexity: O(N2)
Auxiliary Space: O(1)

Linked List-Based Approach: Please refer to the previous post of this article for the linked list-based approach.

Time Complexity: O(N)
Auxiliary Space: O(1)

Recursion-Based Approach: The given problem can also be solved by using recursion. Follow the steps below to solve the problem:

  • Define a recursive function, say RecursiveCloneStack(stack<int> S, stack<int>Des) where S is the source stack and Des is the destination stack:
  • Initialize a stack, say Des to store the destination stack.
  • Now call the function RecursiveCloneStack(S, Des) to copy the elements of the source stack to the destination stack.
  • After completing the above steps, print the elements of the stack Des as the result.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Auxiliary function to copy elements
// of source stack to destination stack
void RecursiveCloneStack(stack<int>& S,
                         stack<int>& Des)
{
    // Base case for Recursion
    if (S.size() == 0)
        return;
 
    // Stores the top element of the
    // source stack
    int val = S.top();
 
    // Removes the top element of the
    // source stack
    S.pop();
 
    // Recursive call to the function
    // with remaining stack
    RecursiveCloneStack(S, Des);
 
    // Push the top element of the source
    // stack into the Destination stack
    Des.push(val);
}
 
// Function to copy the elements of the
// source stack to destination stack
void cloneStack(stack<int>& S)
{
    // Stores the destination stack
    stack<int> Des;
 
    // Recursive function call to copy
    // the source stack to the
    // destination stack
    RecursiveCloneStack(S, Des);
 
    cout << "Destination:- ";
    int f = 0;
 
    // Iterate until stack Des is
    // non-empty
    while (!Des.empty()) {
 
        if (f == 0) {
            cout << Des.top();
            f = 1;
        }
 
        else
            cout << "              "
                 << Des.top();
        Des.pop();
 
        cout << '\n';
    }
}
 
// Driver Code
int main()
{
    stack<int> S;
    S.push(1);
    S.push(2);
    S.push(3);
    S.push(4);
    S.push(5);
    cloneStack(S);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class Main
{
    static Stack<Integer> S = new Stack<Integer>();
    static Stack<Integer> Des = new Stack<Integer>(); // Stores the destination stack
      
    // Auxiliary function to copy elements
    // of source stack to destination stack
    static void RecursiveCloneStack()
    {
       
        // Base case for Recursion
        if (S.size() == 0)
            return;
        
        // Stores the top element of the
        // source stack
        int val = S.peek();
        
        // Removes the top element of the
        // source stack
        S.pop();
        
        // Recursive call to the function
        // with remaining stack
        RecursiveCloneStack();
        
        // Push the top element of the source
        // stack into the Destination stack
        Des.push(val);
    }
      
    // Function to copy the elements of the
    // source stack to destination stack
    static void cloneStack()
    {
        // Recursive function call to copy
        // the source stack to the
        // destination stack
        RecursiveCloneStack();
        
        System.out.print("Destination:- ");
        int f = 0;
        
        // Iterate until stack Des is
        // non-empty
        while (Des.size() > 0) {
        
            if (f == 0) {
                System.out.print(Des.peek());
                f = 1;
            }
        
            else
                System.out.print("              " + Des.peek());
            Des.pop();
        
            System.out.println();
        }
    }
     
  // Driver code
    public static void main(String[] args) {
        S.push(1);
        S.push(2);
        S.push(3);
        S.push(4);
        S.push(5);
        cloneStack();
    }
}
 
// This code is contributed by mukesh07.


Python3




# Python3 program for the above approach
 
S = []
Des = [] # Stores the destination stack
   
# Auxiliary function to copy elements
# of source stack to destination stack
def RecursiveCloneStack():
    
    # Base case for Recursion
    if (len(S) == 0):
        return
     
    # Stores the top element of the
    # source stack
    val = S[-1]
     
    # Removes the top element of the
    # source stack
    S.pop()
     
    # Recursive call to the function
    # with remaining stack
    RecursiveCloneStack()
     
    # Push the top element of the source
    # stack into the Destination stack
    Des.append(val)
   
# Function to copy the elements of the
# source stack to destination stack
def cloneStack():
    # Recursive function call to copy
    # the source stack to the
    # destination stack
    RecursiveCloneStack()
     
    print("Destination:- ", end = "")
    f = 0
     
    # Iterate until stack Des is
    # non-empty
    while len(Des) > 0:
        if (f == 0):
            print(Des[-1], end = "")
            f = 1
     
        else:
            print("             ", Des[-1], end = "")
        Des.pop()
     
        print()
 
S.append(1)
S.append(2)
S.append(3)
S.append(4)
S.append(5)
cloneStack()
 
# This code is contributed by decode2207.


C#




// C# program for the above approach
using System;
using System.Collections;
class GFG {
     
    static Stack S = new Stack();
    static Stack Des = new Stack(); // Stores the destination stack
     
    // Auxiliary function to copy elements
    // of source stack to destination stack
    static void RecursiveCloneStack()
    {
        // Base case for Recursion
        if (S.Count == 0)
            return;
       
        // Stores the top element of the
        // source stack
        int val = (int)S.Peek();
       
        // Removes the top element of the
        // source stack
        S.Pop();
       
        // Recursive call to the function
        // with remaining stack
        RecursiveCloneStack();
       
        // Push the top element of the source
        // stack into the Destination stack
        Des.Push(val);
    }
     
    // Function to copy the elements of the
    // source stack to destination stack
    static void cloneStack()
    {
        // Recursive function call to copy
        // the source stack to the
        // destination stack
        RecursiveCloneStack();
       
        Console.Write("Destination:- ");
        int f = 0;
       
        // Iterate until stack Des is
        // non-empty
        while (Des.Count > 0) {
       
            if (f == 0) {
                Console.Write(Des.Peek());
                f = 1;
            }
       
            else
                Console.Write("              " + Des.Peek());
            Des.Pop();
       
            Console.WriteLine();
        }
    }
 
  static void Main() {
    S.Push(1);
    S.Push(2);
    S.Push(3);
    S.Push(4);
    S.Push(5);
    cloneStack();
  }
}
 
// This code is contributed by divyesh072019.


Javascript




<script>
    // Javascript program for the above approach
    S = [];
    Des = []; // Stores the destination stack
      
    // Auxiliary function to copy elements
    // of source stack to destination stack
    function RecursiveCloneStack()
    {
     
        // Base case for Recursion
        if (S.length == 0)
            return;
        
        // Stores the top element of the
        // source stack
        let val = S[S.length - 1];
        
        // Removes the top element of the
        // source stack
        S.pop();
        
        // Recursive call to the function
        // with remaining stack
        RecursiveCloneStack();
        
        // Push the top element of the source
        // stack into the Destination stack
        Des.push(val);
    }
      
    // Function to copy the elements of the
    // source stack to destination stack
    function cloneStack()
    {
        // Recursive function call to copy
        // the source stack to the
        // destination stack
        RecursiveCloneStack();
        
        document.write("Destination:- ");
        let f = 0;
        
        // Iterate until stack Des is
        // non-empty
        while (Des.length > 0) {
        
            if (f == 0) {
                document.write(Des[Des.length - 1]);
                f = 1;
            }
        
            else{
                document.write("&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp" + Des[Des.length - 1]);
            }
            Des.pop();
        
            document.write("</br>");
        }
    }
     
    S.push(1);
    S.push(2);
    S.push(3);
    S.push(4);
    S.push(5);
    cloneStack();
     
    // This code is contributed by suresh07.
</script>


Output: 

Destination:- 5
              4
              3
              2
              1

 

Time Complexity: O(N) 
Auxiliary Space: O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments