'What is the difference between these two codes? (Python: circular singly linked list)
These are the codes for __iter__ method of a circular singly linked list. But I don't understand the difference between the two.
def __iter__(self):
node = self.head
while node: # i.e. while node is not None
yield node
if node.next == self.head: # i.e. if node.next refers to the first node, i.e. if that is the last node, break
break # without this if condition, the loop will loop forever
node = node.next
and
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
if node == self.tail.next:
break
Solution 1:[1]
def __iter__(self):
node = self.head
while node: # i.e. while node is not None
yield node
if node.next == self.head: # i.e. if node.next refers to the first node, i.e. if that is the last node, break
break # without this if condition, the loop will loop forever
node = node.next
This if
condition doesn't garantee to stop loop over.
There is no way node.next
is equal to self.head
in the above code.
However, as the node will update for every iteration, it will stop the iterations when it reachs node==null
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
if node == self.tail.next:
break
** this code is the same as:**
def __iter__(self):
node = self.head
while node:
yield node
node = node.next
if node == None:
break
As node.tail
is the last element in the linked list, node.tail.next
would be None
.
node.tail
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Endalew Tesfa |