I want to write a function called print_iterator_explicit() which prints all of the items in a linked list by making use of the Iterator. However, you are not permitted to use the standard "for ... in" loop syntax - instead you must create the Iterator object explicitly, and print each item by calling the next() method
Use the iter() and next() methods in your function definition - and remember to handle the StopIteration exception!
Below is what I've tried, but the print_iterator_explicit seems to have some problem which I can only print the first element but not the whole list.
class LinkedListIterator:
def __init__(self, head):
self.current = head
def __next__(self):
if self.current == None:
raise StopIteration
else:
item = self.current.get_data()
self.current = self.current.get_next()
return item
class LinkedList:
def __init__(self):
self.head = None
def __iter__(self):
return LinkedListIterator(self.head)
def add(self, item):
new_node = Node(item)
new_node.set_next(self.head)
self.head = new_node
def print_iterator_explicit(items):
it = items.__iter__()
print(it.__next__())
__iter__and__next__. Useit = iter(items)andnext(it). Also, you should checkspam is None, or sometimesnot spam, but neverspam == Noneexcept in very rare cases.printonce, why would you expect it to print multiple times? You're still going to need a loop. If you can't use aforloop, (a silly restriction, but whatever) that only leaveswhileloops__iter__method that just does areturn self.