I need to reverse a stack in python, my idea is to create an empty stack at the beginning. Then we test whether the original stack is empty, if it is so, then we have nothing to reverse; if not, every time we pop an item out of the original stack, we push it back to the empty stack. This continues until the original stack has nothing to pop out. And finally we rename the storage stack as the original stack, and return it. It should have a reverse order now.
But the problem is, for the unit test below, it never works, it turns out that the temp stack I get does not have a reverse order.
def test_reverse(self):
stack = Stack() stack.push(1) stack.push(2) reverse(stack) self.assertEqual(stack.pop(), 1) self.assertEqual(stack.pop(), 2) self.assertTrue(stack.is_empty())
I really wonder why this does not work, thank you!
stack = reverse(stack)
instead of justreverse(stack)
? - Pradeep Kumartemp = temp.push(stuff)
withtemp.push(stuff)
because you already have the temp stack. Not tested though. Just try. - Pradeep Kumar