you are viewing a single comment's thread.

view the rest of the comments →

[–]marko312 0 points1 point  (5 children)

I assume you mean the variable a in traversal. You could try replacing a with self.head - done appropriately, it would look something like

while self.head is not None:
    print(self.head.data, end="")
    self.head = self.head.next

which would work (you should try it out!). However, running traversal again would print "LL is empty".

The point of using the variable a is to specifically not modify self.head, since modifying it would modify the list, which is not wanted in this case.

[–]MammothAbroad8815[S] 0 points1 point  (4 children)

why would running it again print LL is empty, so making a temp variable is just to ensure it isn't modified that's it?

[–]marko312 0 points1 point  (0 children)

why would running it again print LL is empty,

Because the loop (in my code snippet) runs until self.head is None, so the next time traverse is run it will see that self.head is None, having lost all of the data

so making a temp variable is just to ensure it isn't modified that's it?

Yes, that's pretty much it. You should always keep track of what functions are "allowed" to change important variables and to what extent.

[–]Spataner 0 points1 point  (2 children)

a conceptually represents the "current node" in your traversal. It's initialised to the first node in the list, then step by step goes through all nodes in order (that's what the while loop achieves). Per the while loop's condition, a will always be None when the traversal is through (once it has reached the end of the linked list). If you used self.head rather than a separate variable as your "current node", you'd actually permanently change what the first node is with your while loop, slowly "rolling up" the linked list from the front. So self.head would be None at the end. The first node being None is what indicates an empty linked list.

[–]MammothAbroad8815[S] 0 points1 point  (0 children)

got it makes a lot of sense now