Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Question text Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the

Question text

Iterators provide a systematic way to access all of the elements in a collection. To define an iterator, we need to add the __iter__() method to the class that we want to iterator over. For example, we could define an __iter__() method for the LinkedList class as follows:

 def __iter__(self): return LinkedListIterator(self.head)

This passes the "head" reference to an object of type LinkedListIterator. The LinkedListIterator class must contain the definition of the two methods:

__init__() __next__()

The __next__() method is called repeatedly when a collection is being iterated over, and each time it is called, it returns the next value in the collection.

For this task you can assume that the Node class, and the LinkedList class are provided. You do not need to inclue these classes in your answer. The LinkedList class contains the special __iter__() method defined as shown above. You need to define the LinkedListIterator class. This class will have the following structure:

class LinkedListIterator: def __init__(self, head): def __next__(self):

Reminder: when there are no more elements to iterate over, the __next__() method must raise a StopException.

For example:

Test Result
values = LinkedList() values.add('cherry') values.add('banana') values.add('apple') for v in values: print(v) 
apple banana cherry
values = LinkedList() values.add(1) values.add(2) values.add(3) for v in values: print(v) 
3 2 1

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Big Data Systems A 360-degree Approach

Authors: Jawwad ShamsiMuhammad Khojaye

1st Edition

0429531575, 9780429531576

More Books

Students also viewed these Databases questions