首页 > 代码库 > JAVA类库LinkList的基本实现
JAVA类库LinkList的基本实现
import java.util.Iterator; /** * 类名:MyLinkedList 说明:LinkedList的基本实现 */ public class MyLinkedList<AnyType> implements Iterable { private int theSize = 0; private int modCount = 0; private Node<AnyType> beginMarker; private Node<AnyType> endMarker; private static class Node<AnyType> { public Node(AnyType data, Node<AnyType> prev, Node<AnyType> next) { this.data = http://www.mamicode.com/data;>private Node<AnyType> current = beginMarker.next; private int expectedModCount = modCount; private boolean okToRemove = false; public boolean hasNext() { return current != endMarker; } public AnyType next() { if (modCount != expectedModCount) { throw new java.util.ConcurrentModificationException(); } if (!hasNext()) throw new java.util.NoSuchElementException(); AnyType d = current.data; current = current.next; okToRemove = true; return d; } public void remove() { if (modCount != expectedModCount) { throw new java.util.ConcurrentModificationException(); } if (!okToRemove) throw new IllegalStateException(); MyLinkedList.this.remove(current.prev); okToRemove = false; expectedModCount++; } }; } public String toString() { String s = new String(); for (int i = 0; i < theSize; i++) s += get(i) + " "; return s; } /** * 方法名:MyLinkedList.java 说明:測试 */ public static void main(String[] args) { // TODO Auto-generated method stub MyLinkedList<Integer> list = new MyLinkedList(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); System.out.println(list); list.remove(1); System.out.println(list); list.set(1, 2); System.out.println(list); Iterator ite = list.iterator(); while (ite.hasNext()) { System.out.println(ite.next() + " "); } } }
JAVA类库LinkList的基本实现