public class myLinkedList implements Iterable {
private int thesize; //存储当前链表的长度
private int modcount = 0;
private Node beginMarker; //链表的头节点,其next指向链表的第一个节点
private Node endMarker; //链表的尾节点,其prev指向链表的最后一个节点
public myLinkedList() {
clear();
}
public void clear() {
beginMarker = new Node(null, null, endMarker);
endMarker = new Node(null, beginMarker, null);
thesize = 0;
modcount++;
}
public int size() {
return thesize;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean add(Object x) {
add(thesize, x);
return true;
}
public void add(int idx, Object x) {
addbefore(getNode(idx), x);
}
public Object set(int index, Object newval) {
Node p = getNode(index);
Object oldval = p.date;
p.date = newval;
return oldval;
}
public Object remove(int index) {
return remove(getNode(index));
}
private Object remove(Node p) {
p.prev.next = p.next;
p.next.prev = p.prev;
thesize--;
return p.date;
}
private Node getNode(int index) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException();
}
Node p;
if (index < size() / 2) {
p = beginMarker;
for (int i = 0; i < index; i++) {
p = p.next;
}
return p;
} else {
p = endMarker;
for (int i = size(); i > index; i--) {
p = p.prev;
}
return p;
}
}
private void addbefore(Node p, Object x) {
Node newnode = new Node(x, p.prev, p);
newnode.prev.next = newnode;
p.prev = newnode;
thesize++;
modcount++;
}
@Override
public Iterator iterator() {
return new LinkedListIterator();
}
private static class Node {
public Object date;
public Node prev;
public Node next;
public Node(Object d, Node p, Node n) {
this.date = d;
this.prev = p;
this.next = n;
}
}
public class LinkedListIterator implements Iterator {
private Node current = beginMarker.next;
private int expectedModCount = modcount;
private boolean oktoremove = false;
@Override
public boolean hasNext() {
return current != endMarker;
}
@Override
public Object next() {
if (modcount != expectedModCount) {
throw new ConcurrentModificationException();
}
if (!hasNext()) {
try {
throw new NoSuchFieldException();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
Object nextitem = current.date;
current = current.next;
oktoremove = true;
return nextitem;
}
@Override
public void remove() {
if (modcount != expectedModCount) {
throw new ConcurrentModificationException();
}
if (!hasNext()) {
try {
throw new NoSuchFieldException();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
// myLinkedList.this.remove(current.prev);
new myLinkedList().remove(current.prev);
oktoremove = false;
expectedModCount++;
}
@Override
public void forEachRemaining(Consumer action) {
}
}
}
用链表实现LinkedList
最新推荐文章于 2022-07-05 14:51:16 发布