2 * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation. Oracle designates this
8 * particular file as subject to the "Classpath" exception as provided
9 * by Oracle in the LICENSE file that accompanied this code.
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
29 * Doubly-linked list implementation of the {@code List} and {@code Deque}
30 * interfaces. Implements all optional list operations, and permits all
31 * elements (including {@code null}).
33 * <p>All of the operations perform as could be expected for a doubly-linked
34 * list. Operations that index into the list will traverse the list from
35 * the beginning or the end, whichever is closer to the specified index.
37 * <p><strong>Note that this implementation is not synchronized.</strong>
38 * If multiple threads access a linked list concurrently, and at least
39 * one of the threads modifies the list structurally, it <i>must</i> be
40 * synchronized externally. (A structural modification is any operation
41 * that adds or deletes one or more elements; merely setting the value of
42 * an element is not a structural modification.) This is typically
43 * accomplished by synchronizing on some object that naturally
44 * encapsulates the list.
46 * If no such object exists, the list should be "wrapped" using the
47 * {@link Collections#synchronizedList Collections.synchronizedList}
48 * method. This is best done at creation time, to prevent accidental
49 * unsynchronized access to the list:<pre>
50 * List list = Collections.synchronizedList(new LinkedList(...));</pre>
52 * <p>The iterators returned by this class's {@code iterator} and
53 * {@code listIterator} methods are <i>fail-fast</i>: if the list is
54 * structurally modified at any time after the iterator is created, in
55 * any way except through the Iterator's own {@code remove} or
56 * {@code add} methods, the iterator will throw a {@link
57 * ConcurrentModificationException}. Thus, in the face of concurrent
58 * modification, the iterator fails quickly and cleanly, rather than
59 * risking arbitrary, non-deterministic behavior at an undetermined
62 * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
63 * as it is, generally speaking, impossible to make any hard guarantees in the
64 * presence of unsynchronized concurrent modification. Fail-fast iterators
65 * throw {@code ConcurrentModificationException} on a best-effort basis.
66 * Therefore, it would be wrong to write a program that depended on this
67 * exception for its correctness: <i>the fail-fast behavior of iterators
68 * should be used only to detect bugs.</i>
70 * <p>This class is a member of the
71 * <a href="{@docRoot}/../technotes/guides/collections/index.html">
72 * Java Collections Framework</a>.
78 * @param <E> the type of elements held in this collection
81 public class LinkedList<E>
82 extends AbstractSequentialList<E>
83 implements List<E>, Deque<E>, Cloneable, java.io.Serializable
85 transient int size = 0;
88 * Pointer to first node.
89 * Invariant: (first == null && last == null) ||
90 * (first.prev == null && first.item != null)
92 transient Node<E> first;
95 * Pointer to last node.
96 * Invariant: (first == null && last == null) ||
97 * (last.next == null && last.item != null)
99 transient Node<E> last;
102 * Constructs an empty list.
104 public LinkedList() {
108 * Constructs a list containing the elements of the specified
109 * collection, in the order they are returned by the collection's
112 * @param c the collection whose elements are to be placed into this list
113 * @throws NullPointerException if the specified collection is null
115 public LinkedList(Collection<? extends E> c) {
121 * Links e as first element.
123 private void linkFirst(E e) {
124 final Node<E> f = first;
125 final Node<E> newNode = new Node<>(null, e, f);
136 * Links e as last element.
139 final Node<E> l = last;
140 final Node<E> newNode = new Node<>(l, e, null);
151 * Inserts element e before non-null Node succ.
153 void linkBefore(E e, Node<E> succ) {
154 // assert succ != null;
155 final Node<E> pred = succ.prev;
156 final Node<E> newNode = new Node<>(pred, e, succ);
167 * Unlinks non-null first node f.
169 private E unlinkFirst(Node<E> f) {
170 // assert f == first && f != null;
171 final E element = f.item;
172 final Node<E> next = f.next;
174 f.next = null; // help GC
186 * Unlinks non-null last node l.
188 private E unlinkLast(Node<E> l) {
189 // assert l == last && l != null;
190 final E element = l.item;
191 final Node<E> prev = l.prev;
193 l.prev = null; // help GC
205 * Unlinks non-null node x.
207 E unlink(Node<E> x) {
209 final E element = x.item;
210 final Node<E> next = x.next;
211 final Node<E> prev = x.prev;
234 * Returns the first element in this list.
236 * @return the first element in this list
237 * @throws NoSuchElementException if this list is empty
239 public E getFirst() {
240 final Node<E> f = first;
242 throw new NoSuchElementException();
247 * Returns the last element in this list.
249 * @return the last element in this list
250 * @throws NoSuchElementException if this list is empty
253 final Node<E> l = last;
255 throw new NoSuchElementException();
260 * Removes and returns the first element from this list.
262 * @return the first element from this list
263 * @throws NoSuchElementException if this list is empty
265 public E removeFirst() {
266 final Node<E> f = first;
268 throw new NoSuchElementException();
269 return unlinkFirst(f);
273 * Removes and returns the last element from this list.
275 * @return the last element from this list
276 * @throws NoSuchElementException if this list is empty
278 public E removeLast() {
279 final Node<E> l = last;
281 throw new NoSuchElementException();
282 return unlinkLast(l);
286 * Inserts the specified element at the beginning of this list.
288 * @param e the element to add
290 public void addFirst(E e) {
295 * Appends the specified element to the end of this list.
297 * <p>This method is equivalent to {@link #add}.
299 * @param e the element to add
301 public void addLast(E e) {
306 * Returns {@code true} if this list contains the specified element.
307 * More formally, returns {@code true} if and only if this list contains
308 * at least one element {@code e} such that
309 * <tt>(o==null ? e==null : o.equals(e))</tt>.
311 * @param o element whose presence in this list is to be tested
312 * @return {@code true} if this list contains the specified element
314 public boolean contains(Object o) {
315 return indexOf(o) != -1;
319 * Returns the number of elements in this list.
321 * @return the number of elements in this list
328 * Appends the specified element to the end of this list.
330 * <p>This method is equivalent to {@link #addLast}.
332 * @param e element to be appended to this list
333 * @return {@code true} (as specified by {@link Collection#add})
335 public boolean add(E e) {
341 * Removes the first occurrence of the specified element from this list,
342 * if it is present. If this list does not contain the element, it is
343 * unchanged. More formally, removes the element with the lowest index
344 * {@code i} such that
345 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
346 * (if such an element exists). Returns {@code true} if this list
347 * contained the specified element (or equivalently, if this list
348 * changed as a result of the call).
350 * @param o element to be removed from this list, if present
351 * @return {@code true} if this list contained the specified element
353 public boolean remove(Object o) {
355 for (Node<E> x = first; x != null; x = x.next) {
356 if (x.item == null) {
362 for (Node<E> x = first; x != null; x = x.next) {
363 if (o.equals(x.item)) {
373 * Appends all of the elements in the specified collection to the end of
374 * this list, in the order that they are returned by the specified
375 * collection's iterator. The behavior of this operation is undefined if
376 * the specified collection is modified while the operation is in
377 * progress. (Note that this will occur if the specified collection is
378 * this list, and it's nonempty.)
380 * @param c collection containing elements to be added to this list
381 * @return {@code true} if this list changed as a result of the call
382 * @throws NullPointerException if the specified collection is null
384 public boolean addAll(Collection<? extends E> c) {
385 return addAll(size, c);
389 * Inserts all of the elements in the specified collection into this
390 * list, starting at the specified position. Shifts the element
391 * currently at that position (if any) and any subsequent elements to
392 * the right (increases their indices). The new elements will appear
393 * in the list in the order that they are returned by the
394 * specified collection's iterator.
396 * @param index index at which to insert the first element
397 * from the specified collection
398 * @param c collection containing elements to be added to this list
399 * @return {@code true} if this list changed as a result of the call
400 * @throws IndexOutOfBoundsException {@inheritDoc}
401 * @throws NullPointerException if the specified collection is null
403 public boolean addAll(int index, Collection<? extends E> c) {
404 checkPositionIndex(index);
406 Object[] a = c.toArray();
407 int numNew = a.length;
421 @SuppressWarnings("unchecked") E e = (E) o;
422 Node<E> newNode = new Node<>(pred, e, null);
443 * Removes all of the elements from this list.
444 * The list will be empty after this call returns.
446 public void clear() {
447 // Clearing all of the links between nodes is "unnecessary", but:
448 // - helps a generational GC if the discarded nodes inhabit
449 // more than one generation
450 // - is sure to free memory even if there is a reachable Iterator
451 for (Node<E> x = first; x != null; ) {
452 Node<E> next = x.next;
464 // Positional Access Operations
467 * Returns the element at the specified position in this list.
469 * @param index index of the element to return
470 * @return the element at the specified position in this list
471 * @throws IndexOutOfBoundsException {@inheritDoc}
473 public E get(int index) {
474 checkElementIndex(index);
475 return node(index).item;
479 * Replaces the element at the specified position in this list with the
482 * @param index index of the element to replace
483 * @param element element to be stored at the specified position
484 * @return the element previously at the specified position
485 * @throws IndexOutOfBoundsException {@inheritDoc}
487 public E set(int index, E element) {
488 checkElementIndex(index);
489 Node<E> x = node(index);
496 * Inserts the specified element at the specified position in this list.
497 * Shifts the element currently at that position (if any) and any
498 * subsequent elements to the right (adds one to their indices).
500 * @param index index at which the specified element is to be inserted
501 * @param element element to be inserted
502 * @throws IndexOutOfBoundsException {@inheritDoc}
504 public void add(int index, E element) {
505 checkPositionIndex(index);
510 linkBefore(element, node(index));
514 * Removes the element at the specified position in this list. Shifts any
515 * subsequent elements to the left (subtracts one from their indices).
516 * Returns the element that was removed from the list.
518 * @param index the index of the element to be removed
519 * @return the element previously at the specified position
520 * @throws IndexOutOfBoundsException {@inheritDoc}
522 public E remove(int index) {
523 checkElementIndex(index);
524 return unlink(node(index));
528 * Tells if the argument is the index of an existing element.
530 private boolean isElementIndex(int index) {
531 return index >= 0 && index < size;
535 * Tells if the argument is the index of a valid position for an
536 * iterator or an add operation.
538 private boolean isPositionIndex(int index) {
539 return index >= 0 && index <= size;
543 * Constructs an IndexOutOfBoundsException detail message.
544 * Of the many possible refactorings of the error handling code,
545 * this "outlining" performs best with both server and client VMs.
547 private String outOfBoundsMsg(int index) {
548 return "Index: "+index+", Size: "+size;
551 private void checkElementIndex(int index) {
552 if (!isElementIndex(index))
553 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
556 private void checkPositionIndex(int index) {
557 if (!isPositionIndex(index))
558 throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
562 * Returns the (non-null) Node at the specified element index.
564 Node<E> node(int index) {
565 // assert isElementIndex(index);
567 if (index < (size >> 1)) {
569 for (int i = 0; i < index; i++)
574 for (int i = size - 1; i > index; i--)
583 * Returns the index of the first occurrence of the specified element
584 * in this list, or -1 if this list does not contain the element.
585 * More formally, returns the lowest index {@code i} such that
586 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
587 * or -1 if there is no such index.
589 * @param o element to search for
590 * @return the index of the first occurrence of the specified element in
591 * this list, or -1 if this list does not contain the element
593 public int indexOf(Object o) {
596 for (Node<E> x = first; x != null; x = x.next) {
602 for (Node<E> x = first; x != null; x = x.next) {
603 if (o.equals(x.item))
612 * Returns the index of the last occurrence of the specified element
613 * in this list, or -1 if this list does not contain the element.
614 * More formally, returns the highest index {@code i} such that
615 * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
616 * or -1 if there is no such index.
618 * @param o element to search for
619 * @return the index of the last occurrence of the specified element in
620 * this list, or -1 if this list does not contain the element
622 public int lastIndexOf(Object o) {
625 for (Node<E> x = last; x != null; x = x.prev) {
631 for (Node<E> x = last; x != null; x = x.prev) {
633 if (o.equals(x.item))
643 * Retrieves, but does not remove, the head (first element) of this list.
645 * @return the head of this list, or {@code null} if this list is empty
649 final Node<E> f = first;
650 return (f == null) ? null : f.item;
654 * Retrieves, but does not remove, the head (first element) of this list.
656 * @return the head of this list
657 * @throws NoSuchElementException if this list is empty
665 * Retrieves and removes the head (first element) of this list.
667 * @return the head of this list, or {@code null} if this list is empty
671 final Node<E> f = first;
672 return (f == null) ? null : unlinkFirst(f);
676 * Retrieves and removes the head (first element) of this list.
678 * @return the head of this list
679 * @throws NoSuchElementException if this list is empty
683 return removeFirst();
687 * Adds the specified element as the tail (last element) of this list.
689 * @param e the element to add
690 * @return {@code true} (as specified by {@link Queue#offer})
693 public boolean offer(E e) {
699 * Inserts the specified element at the front of this list.
701 * @param e the element to insert
702 * @return {@code true} (as specified by {@link Deque#offerFirst})
705 public boolean offerFirst(E e) {
711 * Inserts the specified element at the end of this list.
713 * @param e the element to insert
714 * @return {@code true} (as specified by {@link Deque#offerLast})
717 public boolean offerLast(E e) {
723 * Retrieves, but does not remove, the first element of this list,
724 * or returns {@code null} if this list is empty.
726 * @return the first element of this list, or {@code null}
727 * if this list is empty
730 public E peekFirst() {
731 final Node<E> f = first;
732 return (f == null) ? null : f.item;
736 * Retrieves, but does not remove, the last element of this list,
737 * or returns {@code null} if this list is empty.
739 * @return the last element of this list, or {@code null}
740 * if this list is empty
743 public E peekLast() {
744 final Node<E> l = last;
745 return (l == null) ? null : l.item;
749 * Retrieves and removes the first element of this list,
750 * or returns {@code null} if this list is empty.
752 * @return the first element of this list, or {@code null} if
756 public E pollFirst() {
757 final Node<E> f = first;
758 return (f == null) ? null : unlinkFirst(f);
762 * Retrieves and removes the last element of this list,
763 * or returns {@code null} if this list is empty.
765 * @return the last element of this list, or {@code null} if
769 public E pollLast() {
770 final Node<E> l = last;
771 return (l == null) ? null : unlinkLast(l);
775 * Pushes an element onto the stack represented by this list. In other
776 * words, inserts the element at the front of this list.
778 * <p>This method is equivalent to {@link #addFirst}.
780 * @param e the element to push
783 public void push(E e) {
788 * Pops an element from the stack represented by this list. In other
789 * words, removes and returns the first element of this list.
791 * <p>This method is equivalent to {@link #removeFirst()}.
793 * @return the element at the front of this list (which is the top
794 * of the stack represented by this list)
795 * @throws NoSuchElementException if this list is empty
799 return removeFirst();
803 * Removes the first occurrence of the specified element in this
804 * list (when traversing the list from head to tail). If the list
805 * does not contain the element, it is unchanged.
807 * @param o element to be removed from this list, if present
808 * @return {@code true} if the list contained the specified element
811 public boolean removeFirstOccurrence(Object o) {
816 * Removes the last occurrence of the specified element in this
817 * list (when traversing the list from head to tail). If the list
818 * does not contain the element, it is unchanged.
820 * @param o element to be removed from this list, if present
821 * @return {@code true} if the list contained the specified element
824 public boolean removeLastOccurrence(Object o) {
826 for (Node<E> x = last; x != null; x = x.prev) {
827 if (x.item == null) {
833 for (Node<E> x = last; x != null; x = x.prev) {
834 if (o.equals(x.item)) {
844 * Returns a list-iterator of the elements in this list (in proper
845 * sequence), starting at the specified position in the list.
846 * Obeys the general contract of {@code List.listIterator(int)}.<p>
848 * The list-iterator is <i>fail-fast</i>: if the list is structurally
849 * modified at any time after the Iterator is created, in any way except
850 * through the list-iterator's own {@code remove} or {@code add}
851 * methods, the list-iterator will throw a
852 * {@code ConcurrentModificationException}. Thus, in the face of
853 * concurrent modification, the iterator fails quickly and cleanly, rather
854 * than risking arbitrary, non-deterministic behavior at an undetermined
855 * time in the future.
857 * @param index index of the first element to be returned from the
858 * list-iterator (by a call to {@code next})
859 * @return a ListIterator of the elements in this list (in proper
860 * sequence), starting at the specified position in the list
861 * @throws IndexOutOfBoundsException {@inheritDoc}
862 * @see List#listIterator(int)
864 public ListIterator<E> listIterator(int index) {
865 checkPositionIndex(index);
866 return new ListItr(index);
869 private class ListItr implements ListIterator<E> {
870 private Node<E> lastReturned = null;
871 private Node<E> next;
872 private int nextIndex;
873 private int expectedModCount = modCount;
876 // assert isPositionIndex(index);
877 next = (index == size) ? null : node(index);
881 public boolean hasNext() {
882 return nextIndex < size;
886 checkForComodification();
888 throw new NoSuchElementException();
893 return lastReturned.item;
896 public boolean hasPrevious() {
897 return nextIndex > 0;
900 public E previous() {
901 checkForComodification();
903 throw new NoSuchElementException();
905 lastReturned = next = (next == null) ? last : next.prev;
907 return lastReturned.item;
910 public int nextIndex() {
914 public int previousIndex() {
915 return nextIndex - 1;
918 public void remove() {
919 checkForComodification();
920 if (lastReturned == null)
921 throw new IllegalStateException();
923 Node<E> lastNext = lastReturned.next;
924 unlink(lastReturned);
925 if (next == lastReturned)
933 public void set(E e) {
934 if (lastReturned == null)
935 throw new IllegalStateException();
936 checkForComodification();
937 lastReturned.item = e;
940 public void add(E e) {
941 checkForComodification();
951 final void checkForComodification() {
952 if (modCount != expectedModCount)
953 throw new ConcurrentModificationException();
957 private static class Node<E> {
962 Node(Node<E> prev, E element, Node<E> next) {
972 public Iterator<E> descendingIterator() {
973 return new DescendingIterator();
977 * Adapter to provide descending iterators via ListItr.previous
979 private class DescendingIterator implements Iterator<E> {
980 private final ListItr itr = new ListItr(size());
981 public boolean hasNext() {
982 return itr.hasPrevious();
985 return itr.previous();
987 public void remove() {
992 @SuppressWarnings("unchecked")
993 private LinkedList<E> superClone() {
995 return (LinkedList<E>) super.clone();
996 } catch (CloneNotSupportedException e) {
997 throw new InternalError();
1002 * Returns a shallow copy of this {@code LinkedList}. (The elements
1003 * themselves are not cloned.)
1005 * @return a shallow copy of this {@code LinkedList} instance
1007 public Object clone() {
1008 LinkedList<E> clone = superClone();
1010 // Put clone into "virgin" state
1011 clone.first = clone.last = null;
1015 // Initialize clone with our elements
1016 for (Node<E> x = first; x != null; x = x.next)
1023 * Returns an array containing all of the elements in this list
1024 * in proper sequence (from first to last element).
1026 * <p>The returned array will be "safe" in that no references to it are
1027 * maintained by this list. (In other words, this method must allocate
1028 * a new array). The caller is thus free to modify the returned array.
1030 * <p>This method acts as bridge between array-based and collection-based
1033 * @return an array containing all of the elements in this list
1034 * in proper sequence
1036 public Object[] toArray() {
1037 Object[] result = new Object[size];
1039 for (Node<E> x = first; x != null; x = x.next)
1040 result[i++] = x.item;
1045 * Returns an array containing all of the elements in this list in
1046 * proper sequence (from first to last element); the runtime type of
1047 * the returned array is that of the specified array. If the list fits
1048 * in the specified array, it is returned therein. Otherwise, a new
1049 * array is allocated with the runtime type of the specified array and
1050 * the size of this list.
1052 * <p>If the list fits in the specified array with room to spare (i.e.,
1053 * the array has more elements than the list), the element in the array
1054 * immediately following the end of the list is set to {@code null}.
1055 * (This is useful in determining the length of the list <i>only</i> if
1056 * the caller knows that the list does not contain any null elements.)
1058 * <p>Like the {@link #toArray()} method, this method acts as bridge between
1059 * array-based and collection-based APIs. Further, this method allows
1060 * precise control over the runtime type of the output array, and may,
1061 * under certain circumstances, be used to save allocation costs.
1063 * <p>Suppose {@code x} is a list known to contain only strings.
1064 * The following code can be used to dump the list into a newly
1065 * allocated array of {@code String}:
1068 * String[] y = x.toArray(new String[0]);</pre>
1070 * Note that {@code toArray(new Object[0])} is identical in function to
1071 * {@code toArray()}.
1073 * @param a the array into which the elements of the list are to
1074 * be stored, if it is big enough; otherwise, a new array of the
1075 * same runtime type is allocated for this purpose.
1076 * @return an array containing the elements of the list
1077 * @throws ArrayStoreException if the runtime type of the specified array
1078 * is not a supertype of the runtime type of every element in
1080 * @throws NullPointerException if the specified array is null
1082 @SuppressWarnings("unchecked")
1083 public <T> T[] toArray(T[] a) {
1084 if (a.length < size)
1085 a = (T[])java.lang.reflect.Array.newInstance(
1086 a.getClass().getComponentType(), size);
1088 Object[] result = a;
1089 for (Node<E> x = first; x != null; x = x.next)
1090 result[i++] = x.item;
1092 if (a.length > size)
1098 private static final long serialVersionUID = 876323262645176354L;