public class LinkedList implements List{
transient int size = 0;
transient Node first;
transient Node last;
public LinkedList() {
}
public E get(int index) {
return node(index).item;
}
//@TODO BASEë¡
public ListIterator listIterator() {
return listIterator(0);
}
public ListIterator listIterator(int index) {
return new ListItr(index);
}
public int size(){
return size;
}
public boolean isEmpty(){
return size == 0;
}
public boolean add(E e){
linkLast(e);
return true;
}
public boolean remove(Object o){
if (o == null) {
for (Node x = first; x != null; x = x.next) {
if (x.item == null) {
unlink(x);
return true;
}
}
} else {
for (Node x = first; x != null; x = x.next) {
if (o.equals(x.item)) {
unlink(x);
return true;
}
}
}
return false;
}
private void linkFirst(E e) {
final Node f = first;
final Node newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
}
void linkLast(E e){
final Node l = last;
final Node newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
}
E unlink(Node x) {
// assert x != null;
final E element = x.item;
final Node next = x.next;
final Node prev = x.prev;
if (prev == null) {
first = next;
} else {
prev.next = next;
x.prev = null;
}
if (next == null) {
last = prev;
} else {
next.prev = prev;
x.next = null;
}
x.item = null;
size--;
return element;
}
Node node(int index) {
if (index < (size >> 1)) {
Node x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
//@TODO BASEë¡ ë³ê²½
public Iterator iterator() {
return new ListItr(0);
}
// ì¸ë¶ììë ì ê·¼ ë¶ê°ë¥í InnerClass
// static Inner class ììë static variable ì ì¸ ê°ë¥í¨
private static class Node {
E item;
Node next;
Node prev;
Node(Node prev, E element, Node next){
this.prev = prev;
this.item = element;
this.next = next;
}
}
private class ListItr implements ListIterator {
private Node lastReturned = null;
private Node next;
private int nextIndex;
ListItr(int index) {
next = (index == size) ? null : node(index);
nextIndex = index;
}
public boolean hasNext() {
return nextIndex < size;
}
public E next() {
if (!hasNext())
{
}
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.item;
}
public void remove() {
if (lastReturned == null)
{
}
Node lastNext = lastReturned.next;
unlink(lastReturned);
if (next == lastReturned)
next = lastNext;
else
nextIndex--;
lastReturned = null;
}
}
}