0

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.

Community
  • 1
  • 1
Nilashish C
  • 375
  • 2
  • 11

1 Answers1

0

You need an instance variable to maintain the iterator's state between calls to next(). Also, __next__ is not a generator function, it merely returns the next element, so do not use yield there:

def __init__(self, ...):
    # ...
    self.iter_node = None  # maintain state of iterator

def __iter__(self):
    return self

def next(self):
    if self.iter_node is None  # reset iterator to allow repeated iteration
        self.iter_node = self.head or 'XXX'  # dummy for to signal end
    if self.iter_node != 'XXX':
        rval = self.iter_node.data
        self.iter_node = self.iter_node.nextNode or 'XXX'
        return rval
    else:
        self.iter_node = None
        raise StopIteration
user2390182
  • 72,016
  • 6
  • 67
  • 89