0
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)

I am getting an error:

RecursionError: maximum recursion depth exceeded while calling a Python object.

2
  • this is your answer that you expected? Commented May 6, 2020 at 9:24
  • Thanks a lot @BenyGj. Commented May 6, 2020 at 13:22

1 Answer 1

1

hi you need to change your reverse_stack you omit to stop the recursion

you can do something like that:

def reverse_stack(stack_q, len_s= None): 

        if len_s is None: 
            len_s = len(stack_q) 
        if len_s in  (0, 1): 
            return  

        stack_q.insert(len(stack_q) - len_s,  stack_q.pop()) 

        len_s -=1        
        reverse_stack(stack_q, len_s) 

let's try it:

a = list(range(1, 10))
a                          
[1, 2, 3, 4, 5, 6, 7, 8, 9]

reverse_stack(a)
a                          
[9, 8, 7, 6, 5, 4, 3, 2, 1]

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot @Beny Gj.The change you suggested is insightful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.