LinkList的实现

时间:2021-09-30 14:31:45
 public class MyLinkedList<AnyType> implements Iterable<AnyType> {
@Override
public Iterator<AnyType> iterator() {
return new LinkedListIterator();
} public class LinkedListIterator implements Iterator<AnyType>{ private Node current = beginMarker.next;
private int expectedModCount = modCount;
private int okToRemove = 0; @Override
public boolean hasNext() {
return current != endMarker;
} @Override
public AnyType next() {
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
if(!hasNext())
throw new NoSuchElementException(); AnyType element = (AnyType)current.data;
current = current.next;
okToRemove++;
return element;
} public void remove(){
if(modCount != expectedModCount)
throw new ConcurrentModificationException();
if(okToRemove>0)
throw new IllegalStateException(); MyLinkedList.this.remove(current.prev);
okToRemove--;
expectedModCount++;
}
} 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;
} private int theSize;
private int modCount = 0;
private Node<AnyType> beginMarker;
private Node<AnyType> endMarker; public void clear(){
beginMarker = new Node<>(null,null,null);//endMarker还没有定义,因此还不能作为参数传入
endMarker = new Node<>(null,beginMarker,null);
beginMarker.next = endMarker; theSize = 0;
modCount++;
} public int size(){
return theSize;
} public boolean isEmpty(){
return (size() == 0);
} public Node<AnyType> getNode(int idx){
if(idx < 0 || idx >= theSize)
throw new IndexOutOfBoundsException();
Node<AnyType> thisNode;
if(idx < size()/2){
thisNode = beginMarker.next;
for(int i = 0; i < idx; i++)
thisNode = thisNode.next;
}
else {
thisNode = endMarker.prev;
for(int i = size(); i > idx; i--)
thisNode = thisNode.prev;
}
return thisNode;
} public void add(int idx,AnyType element){
addBefore(idx,element);
} public void addBefore(int idx, AnyType element){
if(idx < 0 || idx > size()){ //可取的最大值是最后一个的下一个
throw new IndexOutOfBoundsException();
}
Node p = getNode(idx);
Node current = new Node(element,p.prev,p);
p.prev.next = current;
p.prev = current;
theSize++;
modCount++;
} public boolean add(AnyType element){
add(theSize,element);
return true;
} public AnyType set(int idx, AnyType element){
Node p = getNode(idx);
AnyType oldVal = (AnyType) p.data;
p.data = element;
return oldVal;
} public AnyType remove(int idx){
return remove(getNode(idx));
} public AnyType remove(Node p){
p.prev.next = p.next;
p.next.prev = p.prev;
theSize--;
modCount++;
return (AnyType)p.data;
}
}

在链表和其迭代器中都定义modCount来标记当前操作数,是为了防止在两个类的对象中任意一个操作数据时,其他线程将链表改变,
如果modCount不匹配,则说明问题暴漏,即"快速失败".
okToRemove是为了防止删除头结点而设计.