Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reversing a Stack in Python using recursion

I'm doing some practise questions. This one needs to reverse a stack without using any other data structures except another stack.

I know I will need a helper function that appends the pop-ed numbers once the original stack is empty.

Can somebody get me started? I'm stuck here

def flip_stack(s):
    if not s.is_empty():
        temp = s.pop
        flip_stack(s)

Thanks!

The Stack class has pop, push and is_empty functions.

like image 987
isal Avatar asked Nov 13 '22 08:11

isal


1 Answers

def reverse(orig, reversel=None):
    if not reversel:
        reversel = []
    reversel.append(orig.pop())
    if orig:
        reverse(orig, reversel)
    return reversel

stack = [1, 2, 3, 4, 5]
stack = reverse(stack)
print stack
[5, 4, 3, 2, 1]
like image 133
fraxel Avatar answered Dec 22 '22 04:12

fraxel