Data Structures and Algorithms
with Object-Oriented Design Patterns in C# |
Program defines GetEnumerator method of the StackAsLinkedList class. The GetEnumerator method returns an instance of the private class StackAsLinkedlist.Enumerator that implements the IEnumerator interface (lines 5-34).
Program: StackAsLinkedList class GetEnumerator method.
The Enumerator class has two fields, stack and position. The stack field refers to the stack whose elements are being enumerated. The position field is used to keep track of the position in the linked list of the next object to be enumerated.
The purpose of the MoveNext method is to advance the enumerator to the next position and return false whether there are not more elements to be enumerated. In Program elements remain as long as the position is not null. Clearly, the running time of MoveNext is O(1).
The Current property provides a get accessor that returns the current object. It returns the appropriate object in the linked list, provided that the value of the position variable is not null. Otherwise, it throws a InvalidOperationException exception. Clearly, the running time of this accessor is also O(1).