#πŸ”’ reversing a stack?

10 messages Β· Page 1 of 1 (latest)

hearty grotto
#

This is a linked list homework where I need to write a function to convert a string into another string depending on the contents of the original string (e.g. * = backspace, \ = enter, # = del whole line).

I'm given a class Stack with push() pop() and peek(), and I'm meant to use them to store the characters from the string into a stack and then return the stack to reveal the final output.

However when I return the stack, i get the reverse of the output that I am expecting, due to the FILO concept of stacks.

So, I tried to reverse the stack by creating another stack, but the output im getting is NoneNoneNoneNone... , I believe this is due pop() not actually pushing into the new stack? Perhaps I'm meant to use peek instead? I'm sure I'm missing something really obvious, but I cant seem to understand where I'm going wrong.

    reverse_stack = Stack()
    while not stack.isEmpty():
        reverse_stack.push(stack.pop())

    return reverse_stack
gleaming moonBOT
#

@hearty grotto

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

proper dune
#

hi

tall crane
hearty grotto
tall crane
#

ye
you could make it a teeny bit shorter by doing

    reverse_stack = Stack()
    while not stack.isEmpty():
        reverse_stack.push(stack.peek())
        stack.pop()
    return reverse_stack
```but it matters little
hearty grotto
#

oh i see, thanks very much!

gleaming moonBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.

#

πŸ”’ reversing a stack?