public class ListWithTraversal
1: import java.util.Iterator;
2: import java.util.NoSuchElementException;
3: /**
4: A linked implementation of the ADT list that includes iterator
5: operations as ADT operations.
6:
7: @author Frank M. Carrano
8: @author Timothy M. Henry
9: @version 4.0
10: */
11: public class ListWithTraversal<T> implements ListInterface<T>, Iterator<T>
12: {
13: private Node firstNode;
14: private int numberOfEntries;
15: private Node nextNode; // Node containing next entry in iteration
16:
17: public ListWithTraversal()
18: {
19: initializeDataFields();
20: } // end default constructor
21:
22: /* < Implementations of the remaining methods of the ADT list go here;
23: you can see them in Chapter 14, beginning at Segment 14.7.>
24: . . . */
25:
26: // Initializes the class's data fields to indicate an empty list.
27: private void initializeDataFields()
28: {
29: firstNode = null;
30: numberOfEntries = 0;
31: nextNode = null;
32: } // end initializeDataFields
33:
34: // Methods in the interface Iterator:
35: // 15.11
36: public T next()
37: {
38: if (hasNext())
39: {
40: Node returnNode = nextNode; // Get next node
41: nextNode = nextNode.getNextNode(); // Advance iterator
42:
43: return returnNode.getData(); // Return next entry in iteration
44: }
45: else
46: throw new NoSuchElementException("Illegal call to next(); " +
47: "iterator is after end of list.");
48: } // end next
49: // 15.12
50: public boolean hasNext()
51: {
52: return nextNode != null;
53: } // end hasNext
54:
55: // 15.13
56: public void remove()
57: {
58: throw new UnsupportedOperationException("remove() is not " +
59: "supported by this iterator");
60: } // end remove
61: /** Sets the traversal to the beginning of the list.
62: This method is NOT in the interface Iterator. */
63: public void resetTraversal()
64: {
65: nextNode = firstNode;
66: } // end resetTraversal
67:
68: private class Node
69: {
70: private T data; // Entry in list
71: private Node next; // Link to next node
72:
73: private Node(T dataPortion)
74: {
75: data = dataPortion;
76: next = null;
77: } // end constructor
78:
79: private Node(T dataPortion, Node nextNode)
80: {
81: data = dataPortion;
82: next = nextNode;
83: } // end constructor
84:
85: private T getData()
86: {
87: return data;
88: } // end getData
89:
90: private void setData(T newData)
91: {
92: data = newData;
93: } // end setData
94:
95: private Node getNextNode()
96: {
97: return next;
98: } // end getNextNode
99:
100: private void setNextNode(Node nextNode)
101: {
102: next = nextNode;
103: } // end setNextNode
104: } // end Node
105: } // end ListWithTraversal