/* 参考与数据结构与算法分析--Java描述 */ public class MyLinkedList<AnyType> implements Iterable<AnyType>{ private int theSize; private int modCount=0; private Node<AnyType> beginMarker; private Node<AnyType> endMarker; public MyLinkedList(){ clear(); } public void clear(){ beginMarker=new Node<AnyType>(null,null,null); endMarker=new Node<AnyType>(null,beginMarker,null); beginMarker.next=endMarker; theSize=0; modCount++; } private static class Node<AnyType>{ public Node(AnyType d,Node<AnyType> p,Node<AnyType> n){ data=d; prev=p; next=n; } public AnyType data; public Node<AnyType> prev; public Node<AnyType> next; } public int size(){ return theSize; } public boolean isEmpty(){ return size()==0; } public boolean add(AnyType x){ add(size(),x); return true; } public void add(int idx,AnyType x){ addBefore(getNode(idx),x); } private void addBefore(Node<AnyType> p,AnyType x){ Node<AnyType> newNode=new Node<AnyType>(x,p.prev,p); newNode.prev.next=newNode; p.prev=newNode; theSize++; modCount++; } private AnyType remove(Node<AnyType> p){ p.prev.next=p.next; p.next.prev=p.prev; theSize--; modCount++; return p.data; } public AnyType get(int idx){ return getNode(idx).data; } private Node<AnyType> getNode(int idx){ Node<AnyType> p; if(idx<0||idx>size()) throw new IndexOutOfBoundsException(); if(idx<size()/2) { p = beginMarker.next; for (int i = 0; i < idx; i++) p = p.next; }else{ p=endMarker; for(int i=size();i>idx;i--) p=p.prev; } return p; } public java.util.Iterator<AnyType> iterator(){ return new LinkedListIterator(); } public class LinkedListIterator implements java.util.Iterator<AnyType> { private Node<AnyType> current = beginMarker.next; private int expectedModCount = modCount; private boolean okIoRemove = 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 nextItem = current.data; current = current.next; okIoRemove = true; return nextItem; } public void remove(){ if(modCount!=expectedModCount) throw new java.util.ConcurrentModificationException(); if(!okIoRemove) throw new IllegalStateException(); MyLinkedList.this.remove(current.prev); okIoRemove=false; expectedModCount++; } } public static void main(String[] args){ MyLinkedList<String> my=new MyLinkedList<String>(); my.add("你好"); my.add("圣诞快乐"); System.out.println(my.get(1)); } }
mylinkedlist
最新推荐文章于 2021-03-26 22:15:52 发布