Skip to content

Commit 808a997

Browse files
committed
LinkedList(The madman implementation)
1 parent a207f7c commit 808a997

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

group18/935542673/Coding/junit/com/ikook/basic_data_structure/MyLinkedListTest.java

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,5 +111,21 @@ public void testRemoveInt() {
111111
assertEquals("333", list.get(1));
112112

113113
}
114+
115+
@Test
116+
public void testIterator() {
117+
int i = 0;
118+
for(MyIterator iter = list.iterator(); iter.hasNext();) {
119+
Object str = (Object) iter.next();
120+
assertEquals(list.get(i++), str);
121+
}
122+
123+
int j = list.size();
124+
for(MyIterator iter = list.iterator(); iter.hasNext();) {
125+
iter.next();
126+
iter.remove();
127+
assertEquals( --j , list.size());
128+
}
129+
}
114130

115131
}

group18/935542673/Coding/src/com/ikook/basic_data_structure/MyLinkedList.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -299,4 +299,61 @@ public Node(Node previous, Object data, Node next) {
299299
this.next = next;
300300
}
301301
}
302+
303+
/**
304+
* 返回一个迭代器的实现类
305+
* @return
306+
*/
307+
public MyIterator iterator() {
308+
return new LinkIter();
309+
}
310+
311+
/**
312+
* 迭代器的实现类
313+
* @author ikook
314+
*/
315+
private class LinkIter implements MyIterator {
316+
private Node lastRet; //始终指向刚遍历完的节点
317+
private Node next; // 当前指向的节点
318+
private int nextIndex; //当前节点的索引值
319+
320+
LinkIter () {
321+
next = node(0);
322+
nextIndex = 0;
323+
}
324+
325+
@Override
326+
public boolean hasNext() {
327+
return nextIndex < size;
328+
}
329+
330+
@Override
331+
public Object next() {
332+
if(!hasNext()) {
333+
throw new NoSuchElementException("没有找到指定的元素, 迭代器遍历失败");
334+
}
335+
336+
lastRet = next;
337+
next = next.next;
338+
nextIndex++;
339+
return lastRet.data;
340+
}
341+
342+
@Override
343+
public void remove() {
344+
if(lastRet == null) {
345+
throw new IllegalStateException("非法状态异常,删除失败");
346+
}
347+
348+
Node lastNext = lastRet.next;
349+
deleteElement(lastRet);
350+
if(next == lastRet) {
351+
next = lastNext;
352+
} else {
353+
nextIndex--;
354+
}
355+
lastRet = null;
356+
}
357+
358+
}
302359
}

0 commit comments

Comments
 (0)