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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With