Last active
December 19, 2015 16:19
-
-
Save lichenbo/5983282 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LinkedList<E> | |
extends AbstractSequentialList<E> | |
implements List<E>, Deque<E>, Cloneable, java.io.Serializable | |
{ | |
transient int size = 0; | |
transient Node<E> first; | |
transient Node<E> last; | |
public boolean addAll(int index, Collection<? extends E> c) { | |
checkPositionIndex(index); | |
Object[] a = c.toArray(); | |
int numNew = a.length; | |
if (numNew == 0) | |
return false; | |
Node<E> pred, succ; | |
if (index == size) { | |
succ = null; | |
pred = last; | |
} else { | |
succ = node(index); | |
pred = succ.prev; | |
} | |
for (Object o : a) { | |
@SuppressWarnings("unchecked") E e = (E) o; | |
Node<E> newNode = new Node<>(pred, e, null); | |
if (pred == null) | |
first = newNode; | |
else | |
pred.next = newNode; | |
pred = newNode; | |
} | |
if (succ == null) { | |
last = pred; | |
} else { | |
pred.next = succ; | |
succ.prev = pred; | |
} | |
size += numNew; | |
modCount++; | |
return true; | |
} | |
public E get(int index) { | |
checkElementIndex(index); | |
return node(index).item; | |
} | |
Node<E> node(int index) { | |
if (index < (size >> 1)) { | |
Node<E> x = first; | |
for (int i = 0; i < index; i++) | |
x = x.next; | |
return x; | |
} else { | |
Node<E> x = last; | |
for (int i = size - 1; i > index; i--) | |
x = x.prev; | |
return x; | |
} | |
} | |
public Object clone() { | |
LinkedList<E> clone = superClone(); | |
// Put clone into "virgin" state | |
clone.first = clone.last = null; | |
clone.size = 0; | |
clone.modCount = 0; | |
// Initialize clone with our elements | |
for (Node<E> x = first; x != null; x = x.next) | |
clone.add(x.item); | |
return clone; | |
} | |
public Object[] toArray() { | |
Object[] result = new Object[size]; | |
int i = 0; | |
for (Node<E> x = first; x != null; x = x.next) | |
result[i++] = x.item; | |
return result; | |
} | |
public <T> T[] toArray(T[] a) { | |
if (a.length < size) | |
a = (T[])java.lang.reflect.Array.newInstance( | |
a.getClass().getComponentType(), size); | |
int i = 0; | |
Object[] result = a; | |
for (Node<E> x = first; x != null; x = x.next) | |
result[i++] = x.item; | |
if (a.length > size) | |
a[size] = null; | |
return a; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment