Skip to content

Commit 749c285

Browse files
committed
泛型和迭代器
1 parent 19ca2d9 commit 749c285

File tree

3 files changed

+38
-8
lines changed

3 files changed

+38
-8
lines changed

group17/1264835468/src/assignment/BinaryTree.java

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ public BinaryTreeNode<T> deQueue() {
7777
throw new QueueIsEmptyException();
7878
}
7979

80+
// 把所有出队节点放进另一个队列中
8081
public MyQueue<BinaryTreeNode<T>> getResult() {
8182
prepare();
8283
MyQueue<BinaryTreeNode<T>> result = new MyQueue<>();
@@ -86,20 +87,21 @@ public MyQueue<BinaryTreeNode<T>> getResult() {
8687
return result;
8788
}
8889

90+
private void prepare() {
91+
clearQueue();
92+
enQueue(root);
93+
}
94+
8995
public void clearQueue() {
9096
while (!isEmpty()) {
9197
deQueue();
9298
}
9399
}
94100

95-
private void prepare() {
96-
clearQueue();
97-
enQueue(root);
98-
}
99-
100101
@Override
101102
public String toString() {
102103
StringBuilder stringBuilder = new StringBuilder();
104+
103105
Iterator<BinaryTreeNode<T>> iterator = iterator();
104106
while (iterator.hasNext()) {
105107
stringBuilder.append(iterator.next() + "\n");
@@ -114,16 +116,26 @@ public Iterator<BinaryTreeNode<T>> iterator() {
114116
}
115117

116118
private class BFSIterator implements Iterator<BinaryTreeNode<T>> {
117-
MyQueue<BinaryTreeNode<T>> BFSQueue = new BFSNodeQueue().getResult();
119+
MyArrayList<BinaryTreeNode<T>> list;
120+
Iterator<BinaryTreeNode<T>> iterator;
121+
122+
public BFSIterator() {
123+
MyQueue<BinaryTreeNode<T>> BFSQueue = new BFSNodeQueue().getResult();
124+
list = new MyArrayList<>();
125+
while (!BFSQueue.isEmpty()) {
126+
list.add(BFSQueue.deQueue());
127+
}
128+
iterator = list.iterator();
129+
}
118130

119131
@Override
120132
public boolean hasNext() {
121-
return !BFSQueue.isEmpty();
133+
return iterator.hasNext();
122134
}
123135

124136
@Override
125137
public BinaryTreeNode<T> next() {
126-
return BFSQueue.deQueue();
138+
return iterator.next();
127139
}
128140
}
129141

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
package assignment;
2+
3+
public interface Iterable<T> {
4+
Iterator<T> iterator();
5+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package assignment;
2+
3+
public interface List<E> {
4+
public void add(E o);
5+
6+
public void add(int index, E o);
7+
8+
public E get(int index);
9+
10+
public E remove(int index);
11+
12+
public int size();
13+
}

0 commit comments

Comments
 (0)