import sys
import os
Reversing a stack using empty pop and append and without iterations.
we will use recursive call.
def insert_element_at_bottom(stack, item):
if isEmpty(stack):
push(stack, item)
else:
temp = pop(stack)
insert_element_at_bottom(stack, item)
push(stack, temp)
def create_stack():
stack = []
return stack
def push(stack, item):
stack.append(item)
def pop(stack):
if isEmpty(stack):
print("stack underflow")
exit(1)
return stack.pop()
def isEmpty(stack):
return len(stack) == 0
def reverse_stack(stack):
if not isEmpty(stack):
temp = pop(stack)
reverse_stack(stack)
insert_element_at_bottom(stack, temp)
def print_stack(stack):
for i in range(len(stack) - 1, -1, -1):
print(stack[i], end=' ')
print()
driver code
stack = create_stack()
push(stack, str(4))
push(stack, str(3))
push(stack, str(2))
push(stack, str(1))
print("Original stack:")
reverse_stack(stack)
print("Reversed stack:")
print_stack(stack)