#πŸ”’ hard time understanding classes

10 messages Β· Page 1 of 1 (latest)

dim orbit
#

I am getting started in my algo and data structs class and I am having a hard time understanding classes as I havent wrote a single line of python in a while. In a provided file my prof creates a class called SLLNode which is just a node for a SLL which contains the data and next node attributes. Then is there is a singlylinkedlist class where there are methods for it and I am writing the code. She created the append portion which is


    def append(self, data: T) -> None:
        if self.head is None:
            self.head = SLLNode(Data)
            self.tail = self.head
            return

        self.tail.next = SLLNode(data)

        self.tail = self.tail.next

and I am having a hard time understanding how self.tail.next works. I kind of understand that self.tail is an instance of SLLNode and SLLNode has an attribute of next but I cant wrap my head around it.

dawn mossBOT
#

@dim orbit

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.

neat bolt
#

It's just an expression. self is an SLLNode. So is self.tail. So you're just assigning to that .next attribute of self.tail. Draw boxes with arrows, it helps.

#

Unpack it.

tail_node = self.tail
tail_node.next = SLLNode(data)
#

Any clearer?

#

Personally I might write the last 2 lines like this:

end_node = SLLNode(data)
old_tail_node = self.tail
old_tail_node.next = end_node
self.tail = end_node
cerulean bane
#

Draw boxes with arrows, it helps
This sounds so goofy to me, but its very true.
Here is a picture that might visualize a linked list. (just the first result I could find)
img

neat bolt
#

And mapping the above pic to Python, in Python we use None for the null above.

dawn mossBOT
#
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.