rexarski
rexarski

Reputation: 1

How to reverse a stack properly?

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!

Upvotes: 0

Views: 301

Answers (2)

Cody Stott
Cody Stott

Reputation: 484

If you are interested in using first in, first out (FIFO), you should probably be implementing a Queue as your data structure, not a Stack. Common implementations of Queues are also generally more flexible in application for what it seems you are trying to accomplish.

Upvotes: 0

tom
tom

Reputation: 2365

reverse(stack) is producing an answer, then throwing it out. Put it into a new variable; it's not reversing in place.

Upvotes: 1

Related Questions