Skip to content

Commit 3ab6f5e

Browse files
committed
LinkedList Iterator
1 parent bcce0dd commit 3ab6f5e

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

group18/1049843090/src/com/coding/basic/LinkedList.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,4 +202,37 @@ public Node(E data, Node<E> next) {
202202
this.next = next;
203203
}
204204
}
205+
206+
public Iterator iterator(){
207+
return new LinkedListIterator<>();
208+
}
209+
210+
private class LinkedListIterator<E> implements Iterator<E>{
211+
212+
private int cursor;//游标
213+
214+
private int lastRet = -1;//可被删除元素下标
215+
216+
@Override
217+
public boolean hasNext() {
218+
return cursor!=size;
219+
}
220+
221+
@Override
222+
public E next() {
223+
int i = cursor;
224+
cursor++;
225+
return (E) LinkedList.this.get(lastRet=i);
226+
}
227+
228+
@Override
229+
public void remove() {
230+
if(lastRet<0){
231+
throw new IllegalStateException();
232+
}
233+
cursor = lastRet;
234+
LinkedList.this.remove(lastRet);
235+
lastRet = -1;
236+
}
237+
}
205238
}

group18/1049843090/test/com/coding/basic/LinkedListTest.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,4 +115,15 @@ public void removeLast() throws Exception {
115115

116116
}
117117

118+
@Test
119+
public void iterator() throws Exception {
120+
Iterator iterator = linkedList.iterator();
121+
assertEquals(false,iterator.hasNext());
122+
linkedList.add("A");
123+
assertEquals(true,iterator.hasNext());
124+
assertEquals("A",iterator.next());
125+
iterator.remove();
126+
assertEquals(0,linkedList.size());
127+
}
128+
118129
}

0 commit comments

Comments
 (0)