![]() |
VOOZH | about |
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]
Table of Content
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]
Source Stack: 3 2 1 Destination Stack: 3 2 1
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:
Below is given the implementation:
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.