Clone a stack without using extra space | Set 2
Last Updated :
08 Jul, 2024
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.
Python
# 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("                      " + 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>
OutputDestination:- 5
4
3
2
1
Time Complexity: O(N)
Auxiliary Space: Please note that this solution uses auxiliary space of O(N) in the form of recursion call stack. But no explicit space is created in the user program in the form of a data structure.
Similar Reads
Clone a stack without extra space 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) SpaceThe idea
8 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
Reverse a Stack using Queue Given a stack, the task is to reverse the stack using the queue data structure. Examples: Input: Stack: (Top to Bottom) [10 -> 20 -> 30 -> 40]Output: Stack: (Top to Bottom) [40 -> 30 -> 20 -> 10] Input: Stack: [6 -> 5 -> 4]Output: Stack: [4 -> 5 -> 6] Approach: The prob
5 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
What is Stack Data Structure? A Complete Tutorial Stack is a linear data structure that follows LIFO (Last In First Out) Principle, the last element inserted is the first to be popped out. It means both insertion and deletion operations happen at one end only. LIFO(Last In First Out) PrincipleHere are some real world examples of LIFOConsider a stac
4 min read