Data Structures and Algorithms with Object-Oriented Design Patterns in C#
next up previous contents index

GetEnumerator Method

Program gif 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).

   program5620
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 gif 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).


next up previous contents index

Bruno Copyright © 2001 by Bruno R. Preiss, P.Eng. All rights reserved.