Related Articles

# Clone a stack without extra space

• Difficulty Level : Medium
• Last Updated : 09 Aug, 2021

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

```Input : Source:- |3|
|2|
|1|

Output : Destination:- |3|
|2|
|1|

Input : Source:- |a|
|b|
|c|

Output : Destination:- |a|
|b|
|c|```

Approach: In order to solve this without using extra space, we first reverse the source stack, then pop the top elements of the source stack one by one and push it into the destination stack. We follow the below steps to reverse the source stack:

1. Initialize a variable count to 0.
2. Pop the top element from the source stack and store it in variable topVal.
3. Now pop the elements from the source stack and push them into the dest stack until the length of the source stack is equal to count.
4. Push topVal into the source stack and then pop all the elements in the dest stack and push them into the source stack.
5. Increment the value of count.
6. If count is not equal to length of source stack – 1, repeat the process from step-2.

Below is the implementation of the above approach:

## Python3

 `# Python3 program to copy the contents from source stack``# into destination stack without using extra space` `# Define a class for Stack``class` `Stack(``object``):``    ` `    ``def` `__init__(``self``):``        ``self``.stack ``=` `[]``        ` `    ``def` `push(``self``, value):``        ``self``.stack.append(value)``        ` `    ``def` `pop(``self``):``        ``return` `self``.stack.pop()``        ` `    ``def` `length(``self``):``        ``return` `len``(``self``.stack)``        ` `    ``def` `display(``self``):``        ``for` `i ``in` `range``(``len``(``self``.stack)``-``1``, ``-``1``, ``-``1``):``            ``print``(``self``.stack[i])``            ` `        ``print``()``        ` `source ``=` `Stack()     ``# Source Stack``dest ``=` `Stack()         ``# Destination Stack` `source.push(``1``)``source.push(``2``)``source.push(``3``)` `print``(``"Source Stack:"``)``source.display()` `count ``=` `0` `# Reverse the order of the values in source stack``while` `count !``=` `source.length() ``-` `1``:``    ` `    ``topVal ``=` `source.pop()``    ``while` `count !``=` `source.length():``        ``dest.push(source.pop())``        ` `    ``source.push(topVal)``    ``while` `dest.length() !``=` `0``:``        ``source.push(dest.pop())``        ` `    ``count ``+``=` `1` `# Pop the values from source and push into destination stack``while` `source.length() !``=` `0``:``    ``dest.push(source.pop())``    ` `print``(``"Destination Stack:"``)``dest.display()`

Output:

```Source Stack:
3
2
1

Destination Stack:
3
2
1```

Time Complexity: Efficient Approach: A better approach would be to represent the stack as a linked list. Reverse the source stack in the same way we reverse a linked list, pop the top elements of the source stack one by one and push it into the destination stack.
Below is the implementation of the above approach:

## Python3

 `# Python3 program to copy the contents from source stack``# into destination stack without using extra space``# in linear time using Linked List` `class` `StackNode(``object``):``    ` `    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.``next` `=` `None` `# Class for Stack to represent it as Linked list``class` `Stack(``object``):``    ` `    ``def` `__init__(``self``):``        ``self``.top ``=` `None``        ` `    ``def` `push(``self``, value):``        ` `        ``newVal ``=` `StackNode(value)``        ` `        ``if` `self``.top ``=``=` `None``:``            ``self``.top ``=` `newVal``        ` `        ``else``:``            ``newVal.``next` `=` `self``.top``            ``self``.top ``=` `newVal``    ` `    ``def` `pop(``self``):``        ` `        ``val ``=` `self``.top.data``        ``self``.top ``=` `self``.top.``next``        ``return` `val``        ` `    ``def` `display(``self``):``        ` `        ``current ``=` `self``.top``        ``while` `current !``=` `None``:``            ``print``(current.data)``            ``current ``=` `current.``next``            ` `        ``print``()``        ` `    ``def` `reverse(``self``):``        ` `        ``current, temp, prev ``=` `self``.top, ``None``, ``None``        ` `        ``while` `current !``=` `None``:``            ``temp ``=` `current.``next``            ``current.``next` `=` `prev``            ``prev ``=` `current``            ``current ``=` `temp``            ` `        ``self``.top ``=` `prev``    ` `    ``def` `isEmpty(``self``):``        ``return` `self``.top ``=``=` `None``        ` `source ``=` `Stack()        ``# Source Stack``dest ``=` `Stack()          ``# Destination Stack` `source.push(``1``)``source.push(``2``)``source.push(``3``)` `print``(``"Source Stack:"``)``source.display()` `source.reverse()` `# Pop the values from source and push into destination stack``while` `source.isEmpty() !``=` `True``:``    ``dest.push(source.pop())``    ` `print``(``"Destination Stack:"``)``dest.display()`

Output:

```Source Stack:
3
2
1

Destination Stack:
3
2
1```

Time Complexity: Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up