import java.util.Iterator;
import java.util.NoSuchElementException;
public class MyLinkedList<T> implements Iterable<T> {
private int theSize;
private Node<T> first;
private Node<T> last;
public MyLinkedList() {
clear();
}
/**
* 头节点的后指针指向尾节点,尾节点的前指针指向头结点,大小设为0
*/
public void clear() {
first = new Node<T>(null, null, null);
last = new Node<T>(null, first, null);
first.next = last;
theSize = 0;
}
public int size() {
return theSize;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean add(T data) {
insert(size(), data);
return true;
}
public void insert(int index, T data) {
Node<T> p = getNode(index);
Node<T> newNode = new Node(data, p.pre, p.pre.next);
p.pre.next = newNode;
p.pre = newNode;
theSize++;
}
public T get(int index) {
return getNode(index).data;
}
/**
* 将某节点的值替换为新值
* @param index 节点下标
* @param newData 新值
* @return 旧值
*/
public T set(int index, T newData) {
Node<T> p = getNode(index);
T oldData = p.data;
p.data = newData;
return oldData;
}
public T remove(int index) {
return remove(getNode(index));
}
private T remove(Node<T> p) {
p.pre.next = p.next;
p.next.pre = p.pre;
theSize--;
return p.data;
}
private Node<T> getNode(int index){
Node<T> current;
current = first.next;
for(int i=0; i<index; i++) {
current = current.next;
}
return current;
}
@Override
public Iterator<T> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<T>{
private Node<T> current = first.next;
@Override
public boolean hasNext() {
return current != last;
}
@Override
public T next() {
if(!hasNext())
throw new NoSuchElementException();
T data = current.data;
current = current.next;
return data;
}
@Override
public void remove() {
MyLinkedList.this.remove(current.pre);
}
}
private static class Node<T>{
public T data;
public Node<T> pre;
public Node<T> next;
public Node(T data, Node<T> pre, Node<T> next) {
this.data = data;
this.pre = pre;
this.next = next;
}
}
}