How to print elements from a stack?

Asked

Viewed 70 times

1

I have problem formatting output from this program. Below follows the code snippet making the stack impression, then follows the problem img

def __repr__(self):
    r = ""
    pointer = self.top
    while(pointer):
        r = r + str(pointer.data) + " "
        pointer = pointer.next
    return r

inserir a descrição da imagem aqui

  • Just out of curiosity what that would be self.top?

  • I believe the top of the stack

  • Beauty is top of the stack, but that top of the stack is instance of that class?

  • class Stack:
 def __init__(self):
 self.top = None
 self._size = 0 You’re talking about the battery class?

  • kkkk sorry, not manjo much am paying ed for the first time

1 answer

2


You need to add the method strip(). To remove whitespace at the beginning and end of the generated strings.

A possible solution, using your code, would be:

def __repr__(self):
    r = ""
    pointer = self.top
    while(pointer):
        r = r + str(pointer.data) + " "
        pointer = pointer.next
    return r.strip()

This way the expected output will be equal to the response obtained from your program.

  • grateful for the response

Browser other questions tagged

You are not signed in. Login or sign up in order to post.