I am trying to implement a simple Linked List in Python, and sort of trying to use all the Python concepts that I learned in it. I am stuck in implementing a Generator for the class.
Code:
def __iter__(self):
return self
def next(self):
tempNode = self.head
while tempNode:
yield tempNode.data
tempNode = tempNode.nextNode
else:
raise StopIteration
Usage:
list_gen = iter(list1)
print (next(list_gen))
print (next(list_gen))
Output:
generator object next at 0x7ff885b63960
generator object next at 0x7ff885b63960
Neither is it printing the data value of the node, nor is it maintaining the current state of the method [as evident from the addresses returned].
Where am I making the mistake? Thanks in advance.
EDIT I modified the code to:
def next(self):
tempNode = self.head
while tempNode:
tempNode2 = tempNode
tempNode = tempNode.nextNode
return tempNode2.data
else:
raise StopIteration
Now, the node value is printed, but as mentioned earlier, the state is not preserved and the value of the first node is printed every time.