Data Structures and Algorithms
with Object-Oriented Design Patterns in Python|
Program defines the __iter__ method of the StackAsLinkedList class. The __iter__ method returns an instance of the nested class StackAsLinkedlist.Iterator that implements the iterator protocol (lines 3-16).
Program: StackAsLinkedList class __iter__ method.
The Iterator class has two instance attributes, _container and _position. The _container instance attribute refers to the stack whose elements are being enumerated. The _position instance attribute is used to keep track of the position in the linked list of the next object to be enumerated.
The purpose of the _next method is to advance the iterator to the next object in the stack and to raise a StopIteration exception when there are no more elements to be enumerated. In Program elements remain as long as the _position is not None. Clearly, the running time of _next is O(1).