Clone a stack without extra space - GeeksforGeeks

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:  
Initialize a variable count to 0.Pop the top element from the source stack and store it in variable topVal.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.Push topVal into the source stack and then pop all the elements in the dest stack and push them into the source stack.Increment the value of count.If count is not equal to length of source stack – 1, repeat the process from step-2.
Initialize a variable count to 0.
Pop the top element from the source stack and store it in variable topVal.
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.
Push topVal into the source stack and then pop all the elements in the dest stack and push them into the source stack.
Increment the value of count.
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 Stackclass 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 Stackdest = 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 stackwhile 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 stackwhile 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 listclass 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 Stackdest = 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 stackwhile 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:  
pranavkumar8588
Picked
Reverse
Technical Scripter 2018
Linked List
Stack
Technical Scripter
Linked List
Stack
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Swap nodes in a linked list without swapping data
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Circular Singly Linked List | Insertion
Circular Linked List | Set 2 (Traversal)
Stack in Python
Stack Class in Java
Program for Tower of Hanoi
Check for Balanced Brackets in an expression (well-formedness) using Stack
Stack | Set 2 (Infix to Postfix)