1 /*
2  * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
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.
10  *
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).
16  *
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.
20  *
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
23  * questions.
24  */
25 
26 package java.util;
27 
28 import java.io.IOException;
29 import java.io.ObjectInput;
30 import java.io.ObjectOutput;
31 import java.util.function.Consumer;
32 import java.util.function.IntFunction;
33 import java.util.function.Predicate;
34 import java.util.function.UnaryOperator;
35 import java.util.stream.Stream;
36 
37 /**
38  * Doubly-linked list implementation of the {@code List} and {@code Deque}
39  * interfaces.  Implements all optional list operations, and permits all
40  * elements (including {@code null}).
41  *
42  * <p>All of the operations perform as could be expected for a doubly-linked
43  * list.  Operations that index into the list will traverse the list from
44  * the beginning or the end, whichever is closer to the specified index.
45  *
46  * <p><strong>Note that this implementation is not synchronized.</strong>
47  * If multiple threads access a linked list concurrently, and at least
48  * one of the threads modifies the list structurally, it <i>must</i> be
49  * synchronized externally.  (A structural modification is any operation
50  * that adds or deletes one or more elements; merely setting the value of
51  * an element is not a structural modification.)  This is typically
52  * accomplished by synchronizing on some object that naturally
53  * encapsulates the list.
54  *
55  * If no such object exists, the list should be "wrapped" using the
56  * {@link Collections#synchronizedList Collections.synchronizedList}
57  * method.  This is best done at creation time, to prevent accidental
58  * unsynchronized access to the list:<pre>
59  *   List list = Collections.synchronizedList(new LinkedList(...));</pre>
60  *
61  * <p>The iterators returned by this class's {@code iterator} and
62  * {@code listIterator} methods are <i>fail-fast</i>: if the list is
63  * structurally modified at any time after the iterator is created, in
64  * any way except through the Iterator's own {@code remove} or
65  * {@code add} methods, the iterator will throw a {@link
66  * ConcurrentModificationException}.  Thus, in the face of concurrent
67  * modification, the iterator fails quickly and cleanly, rather than
68  * risking arbitrary, non-deterministic behavior at an undetermined
69  * time in the future.
70  *
71  * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
72  * as it is, generally speaking, impossible to make any hard guarantees in the
73  * presence of unsynchronized concurrent modification.  Fail-fast iterators
74  * throw {@code ConcurrentModificationException} on a best-effort basis.
75  * Therefore, it would be wrong to write a program that depended on this
76  * exception for its correctness:   <i>the fail-fast behavior of iterators
77  * should be used only to detect bugs.</i>
78  *
79  * <p>This class is a member of the
80  * <a href="{@docRoot}/java.base/java/util/package-summary.html#CollectionsFramework">
81  * Java Collections Framework</a>.
82  *
83  * @author  Josh Bloch
84  * @see     List
85  * @see     ArrayList
86  * @since 1.2
87  * @param <E> the type of elements held in this collection
88  */
89 
90 public class LinkedList<E>
91     extends AbstractSequentialList<E>
92     implements List<E>, Deque<E>, Cloneable, java.io.Serializable
93 {
94     transient int size = 0;
95 
96     /**
97      * Pointer to first node.
98      */
99     transient Node<E> first;
100 
101     /**
102      * Pointer to last node.
103      */
104     transient Node<E> last;
105 
106     /*
107     void dataStructureInvariants() {
108         assert (size == 0)
109             ? (first == null && last == null)
110             : (first.prev == null && last.next == null);
111     }
112     */
113 
114     /**
115      * Constructs an empty list.
116      */
LinkedList()117     public LinkedList() {
118     }
119 
120     /**
121      * Constructs a list containing the elements of the specified
122      * collection, in the order they are returned by the collection's
123      * iterator.
124      *
125      * @param  c the collection whose elements are to be placed into this list
126      * @throws NullPointerException if the specified collection is null
127      */
LinkedList(Collection<? extends E> c)128     public LinkedList(Collection<? extends E> c) {
129         this();
130         addAll(c);
131     }
132 
133     /**
134      * Links e as first element.
135      */
linkFirst(E e)136     private void linkFirst(E e) {
137         final Node<E> f = first;
138         final Node<E> newNode = new Node<>(null, e, f);
139         first = newNode;
140         if (f == null)
141             last = newNode;
142         else
143             f.prev = newNode;
144         size++;
145         modCount++;
146     }
147 
148     /**
149      * Links e as last element.
150      */
linkLast(E e)151     void linkLast(E e) {
152         final Node<E> l = last;
153         final Node<E> newNode = new Node<>(l, e, null);
154         last = newNode;
155         if (l == null)
156             first = newNode;
157         else
158             l.next = newNode;
159         size++;
160         modCount++;
161     }
162 
163     /**
164      * Inserts element e before non-null Node succ.
165      */
linkBefore(E e, Node<E> succ)166     void linkBefore(E e, Node<E> succ) {
167         // assert succ != null;
168         final Node<E> pred = succ.prev;
169         final Node<E> newNode = new Node<>(pred, e, succ);
170         succ.prev = newNode;
171         if (pred == null)
172             first = newNode;
173         else
174             pred.next = newNode;
175         size++;
176         modCount++;
177     }
178 
179     /**
180      * Unlinks non-null first node f.
181      */
unlinkFirst(Node<E> f)182     private E unlinkFirst(Node<E> f) {
183         // assert f == first && f != null;
184         final E element = f.item;
185         final Node<E> next = f.next;
186         f.item = null;
187         f.next = null; // help GC
188         first = next;
189         if (next == null)
190             last = null;
191         else
192             next.prev = null;
193         size--;
194         modCount++;
195         return element;
196     }
197 
198     /**
199      * Unlinks non-null last node l.
200      */
unlinkLast(Node<E> l)201     private E unlinkLast(Node<E> l) {
202         // assert l == last && l != null;
203         final E element = l.item;
204         final Node<E> prev = l.prev;
205         l.item = null;
206         l.prev = null; // help GC
207         last = prev;
208         if (prev == null)
209             first = null;
210         else
211             prev.next = null;
212         size--;
213         modCount++;
214         return element;
215     }
216 
217     /**
218      * Unlinks non-null node x.
219      */
unlink(Node<E> x)220     E unlink(Node<E> x) {
221         // assert x != null;
222         final E element = x.item;
223         final Node<E> next = x.next;
224         final Node<E> prev = x.prev;
225 
226         if (prev == null) {
227             first = next;
228         } else {
229             prev.next = next;
230             x.prev = null;
231         }
232 
233         if (next == null) {
234             last = prev;
235         } else {
236             next.prev = prev;
237             x.next = null;
238         }
239 
240         x.item = null;
241         size--;
242         modCount++;
243         return element;
244     }
245 
246     /**
247      * Returns the first element in this list.
248      *
249      * @return the first element in this list
250      * @throws NoSuchElementException if this list is empty
251      */
getFirst()252     public E getFirst() {
253         final Node<E> f = first;
254         if (f == null)
255             throw new NoSuchElementException();
256         return f.item;
257     }
258 
259     /**
260      * Returns the last element in this list.
261      *
262      * @return the last element in this list
263      * @throws NoSuchElementException if this list is empty
264      */
getLast()265     public E getLast() {
266         final Node<E> l = last;
267         if (l == null)
268             throw new NoSuchElementException();
269         return l.item;
270     }
271 
272     /**
273      * Removes and returns the first element from this list.
274      *
275      * @return the first element from this list
276      * @throws NoSuchElementException if this list is empty
277      */
removeFirst()278     public E removeFirst() {
279         final Node<E> f = first;
280         if (f == null)
281             throw new NoSuchElementException();
282         return unlinkFirst(f);
283     }
284 
285     /**
286      * Removes and returns the last element from this list.
287      *
288      * @return the last element from this list
289      * @throws NoSuchElementException if this list is empty
290      */
removeLast()291     public E removeLast() {
292         final Node<E> l = last;
293         if (l == null)
294             throw new NoSuchElementException();
295         return unlinkLast(l);
296     }
297 
298     /**
299      * Inserts the specified element at the beginning of this list.
300      *
301      * @param e the element to add
302      */
addFirst(E e)303     public void addFirst(E e) {
304         linkFirst(e);
305     }
306 
307     /**
308      * Appends the specified element to the end of this list.
309      *
310      * <p>This method is equivalent to {@link #add}.
311      *
312      * @param e the element to add
313      */
addLast(E e)314     public void addLast(E e) {
315         linkLast(e);
316     }
317 
318     /**
319      * Returns {@code true} if this list contains the specified element.
320      * More formally, returns {@code true} if and only if this list contains
321      * at least one element {@code e} such that
322      * {@code Objects.equals(o, e)}.
323      *
324      * @param o element whose presence in this list is to be tested
325      * @return {@code true} if this list contains the specified element
326      */
contains(Object o)327     public boolean contains(Object o) {
328         return indexOf(o) >= 0;
329     }
330 
331     /**
332      * Returns the number of elements in this list.
333      *
334      * @return the number of elements in this list
335      */
size()336     public int size() {
337         return size;
338     }
339 
340     /**
341      * Appends the specified element to the end of this list.
342      *
343      * <p>This method is equivalent to {@link #addLast}.
344      *
345      * @param e element to be appended to this list
346      * @return {@code true} (as specified by {@link Collection#add})
347      */
add(E e)348     public boolean add(E e) {
349         linkLast(e);
350         return true;
351     }
352 
353     /**
354      * Removes the first occurrence of the specified element from this list,
355      * if it is present.  If this list does not contain the element, it is
356      * unchanged.  More formally, removes the element with the lowest index
357      * {@code i} such that
358      * {@code Objects.equals(o, get(i))}
359      * (if such an element exists).  Returns {@code true} if this list
360      * contained the specified element (or equivalently, if this list
361      * changed as a result of the call).
362      *
363      * @param o element to be removed from this list, if present
364      * @return {@code true} if this list contained the specified element
365      */
remove(Object o)366     public boolean remove(Object o) {
367         if (o == null) {
368             for (Node<E> x = first; x != null; x = x.next) {
369                 if (x.item == null) {
370                     unlink(x);
371                     return true;
372                 }
373             }
374         } else {
375             for (Node<E> x = first; x != null; x = x.next) {
376                 if (o.equals(x.item)) {
377                     unlink(x);
378                     return true;
379                 }
380             }
381         }
382         return false;
383     }
384 
385     /**
386      * Appends all of the elements in the specified collection to the end of
387      * this list, in the order that they are returned by the specified
388      * collection's iterator.  The behavior of this operation is undefined if
389      * the specified collection is modified while the operation is in
390      * progress.  (Note that this will occur if the specified collection is
391      * this list, and it's nonempty.)
392      *
393      * @param c collection containing elements to be added to this list
394      * @return {@code true} if this list changed as a result of the call
395      * @throws NullPointerException if the specified collection is null
396      */
addAll(Collection<? extends E> c)397     public boolean addAll(Collection<? extends E> c) {
398         return addAll(size, c);
399     }
400 
401     /**
402      * Inserts all of the elements in the specified collection into this
403      * list, starting at the specified position.  Shifts the element
404      * currently at that position (if any) and any subsequent elements to
405      * the right (increases their indices).  The new elements will appear
406      * in the list in the order that they are returned by the
407      * specified collection's iterator.
408      *
409      * @param index index at which to insert the first element
410      *              from the specified collection
411      * @param c collection containing elements to be added to this list
412      * @return {@code true} if this list changed as a result of the call
413      * @throws IndexOutOfBoundsException {@inheritDoc}
414      * @throws NullPointerException if the specified collection is null
415      */
addAll(int index, Collection<? extends E> c)416     public boolean addAll(int index, Collection<? extends E> c) {
417         checkPositionIndex(index);
418 
419         Object[] a = c.toArray();
420         int numNew = a.length;
421         if (numNew == 0)
422             return false;
423 
424         Node<E> pred, succ;
425         if (index == size) {
426             succ = null;
427             pred = last;
428         } else {
429             succ = node(index);
430             pred = succ.prev;
431         }
432 
433         for (Object o : a) {
434             @SuppressWarnings("unchecked") E e = (E) o;
435             Node<E> newNode = new Node<>(pred, e, null);
436             if (pred == null)
437                 first = newNode;
438             else
439                 pred.next = newNode;
440             pred = newNode;
441         }
442 
443         if (succ == null) {
444             last = pred;
445         } else {
446             pred.next = succ;
447             succ.prev = pred;
448         }
449 
450         size += numNew;
451         modCount++;
452         return true;
453     }
454 
455     /**
456      * Removes all of the elements from this list.
457      * The list will be empty after this call returns.
458      */
clear()459     public void clear() {
460         // Clearing all of the links between nodes is "unnecessary", but:
461         // - helps a generational GC if the discarded nodes inhabit
462         //   more than one generation
463         // - is sure to free memory even if there is a reachable Iterator
464         for (Node<E> x = first; x != null; ) {
465             Node<E> next = x.next;
466             x.item = null;
467             x.next = null;
468             x.prev = null;
469             x = next;
470         }
471         first = last = null;
472         size = 0;
473         modCount++;
474     }
475 
476 
477     // Positional Access Operations
478 
479     /**
480      * Returns the element at the specified position in this list.
481      *
482      * @param index index of the element to return
483      * @return the element at the specified position in this list
484      * @throws IndexOutOfBoundsException {@inheritDoc}
485      */
get(int index)486     public E get(int index) {
487         checkElementIndex(index);
488         return node(index).item;
489     }
490 
491     /**
492      * Replaces the element at the specified position in this list with the
493      * specified element.
494      *
495      * @param index index of the element to replace
496      * @param element element to be stored at the specified position
497      * @return the element previously at the specified position
498      * @throws IndexOutOfBoundsException {@inheritDoc}
499      */
set(int index, E element)500     public E set(int index, E element) {
501         checkElementIndex(index);
502         Node<E> x = node(index);
503         E oldVal = x.item;
504         x.item = element;
505         return oldVal;
506     }
507 
508     /**
509      * Inserts the specified element at the specified position in this list.
510      * Shifts the element currently at that position (if any) and any
511      * subsequent elements to the right (adds one to their indices).
512      *
513      * @param index index at which the specified element is to be inserted
514      * @param element element to be inserted
515      * @throws IndexOutOfBoundsException {@inheritDoc}
516      */
add(int index, E element)517     public void add(int index, E element) {
518         checkPositionIndex(index);
519 
520         if (index == size)
521             linkLast(element);
522         else
523             linkBefore(element, node(index));
524     }
525 
526     /**
527      * Removes the element at the specified position in this list.  Shifts any
528      * subsequent elements to the left (subtracts one from their indices).
529      * Returns the element that was removed from the list.
530      *
531      * @param index the index of the element to be removed
532      * @return the element previously at the specified position
533      * @throws IndexOutOfBoundsException {@inheritDoc}
534      */
remove(int index)535     public E remove(int index) {
536         checkElementIndex(index);
537         return unlink(node(index));
538     }
539 
540     /**
541      * Tells if the argument is the index of an existing element.
542      */
isElementIndex(int index)543     private boolean isElementIndex(int index) {
544         return index >= 0 && index < size;
545     }
546 
547     /**
548      * Tells if the argument is the index of a valid position for an
549      * iterator or an add operation.
550      */
isPositionIndex(int index)551     private boolean isPositionIndex(int index) {
552         return index >= 0 && index <= size;
553     }
554 
555     /**
556      * Constructs an IndexOutOfBoundsException detail message.
557      * Of the many possible refactorings of the error handling code,
558      * this "outlining" performs best with both server and client VMs.
559      */
outOfBoundsMsg(int index)560     private String outOfBoundsMsg(int index) {
561         return "Index: "+index+", Size: "+size;
562     }
563 
checkElementIndex(int index)564     private void checkElementIndex(int index) {
565         if (!isElementIndex(index))
566             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
567     }
568 
checkPositionIndex(int index)569     private void checkPositionIndex(int index) {
570         if (!isPositionIndex(index))
571             throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
572     }
573 
574     /**
575      * Returns the (non-null) Node at the specified element index.
576      */
node(int index)577     Node<E> node(int index) {
578         // assert isElementIndex(index);
579 
580         if (index < (size >> 1)) {
581             Node<E> x = first;
582             for (int i = 0; i < index; i++)
583                 x = x.next;
584             return x;
585         } else {
586             Node<E> x = last;
587             for (int i = size - 1; i > index; i--)
588                 x = x.prev;
589             return x;
590         }
591     }
592 
593     // Search Operations
594 
595     /**
596      * Returns the index of the first occurrence of the specified element
597      * in this list, or -1 if this list does not contain the element.
598      * More formally, returns the lowest index {@code i} such that
599      * {@code Objects.equals(o, get(i))},
600      * or -1 if there is no such index.
601      *
602      * @param o element to search for
603      * @return the index of the first occurrence of the specified element in
604      *         this list, or -1 if this list does not contain the element
605      */
indexOf(Object o)606     public int indexOf(Object o) {
607         int index = 0;
608         if (o == null) {
609             for (Node<E> x = first; x != null; x = x.next) {
610                 if (x.item == null)
611                     return index;
612                 index++;
613             }
614         } else {
615             for (Node<E> x = first; x != null; x = x.next) {
616                 if (o.equals(x.item))
617                     return index;
618                 index++;
619             }
620         }
621         return -1;
622     }
623 
624     /**
625      * Returns the index of the last occurrence of the specified element
626      * in this list, or -1 if this list does not contain the element.
627      * More formally, returns the highest index {@code i} such that
628      * {@code Objects.equals(o, get(i))},
629      * or -1 if there is no such index.
630      *
631      * @param o element to search for
632      * @return the index of the last occurrence of the specified element in
633      *         this list, or -1 if this list does not contain the element
634      */
lastIndexOf(Object o)635     public int lastIndexOf(Object o) {
636         int index = size;
637         if (o == null) {
638             for (Node<E> x = last; x != null; x = x.prev) {
639                 index--;
640                 if (x.item == null)
641                     return index;
642             }
643         } else {
644             for (Node<E> x = last; x != null; x = x.prev) {
645                 index--;
646                 if (o.equals(x.item))
647                     return index;
648             }
649         }
650         return -1;
651     }
652 
653     // Queue operations.
654 
655     /**
656      * Retrieves, but does not remove, the head (first element) of this list.
657      *
658      * @return the head of this list, or {@code null} if this list is empty
659      * @since 1.5
660      */
peek()661     public E peek() {
662         final Node<E> f = first;
663         return (f == null) ? null : f.item;
664     }
665 
666     /**
667      * Retrieves, but does not remove, the head (first element) of this list.
668      *
669      * @return the head of this list
670      * @throws NoSuchElementException if this list is empty
671      * @since 1.5
672      */
element()673     public E element() {
674         return getFirst();
675     }
676 
677     /**
678      * Retrieves and removes the head (first element) of this list.
679      *
680      * @return the head of this list, or {@code null} if this list is empty
681      * @since 1.5
682      */
poll()683     public E poll() {
684         final Node<E> f = first;
685         return (f == null) ? null : unlinkFirst(f);
686     }
687 
688     /**
689      * Retrieves and removes the head (first element) of this list.
690      *
691      * @return the head of this list
692      * @throws NoSuchElementException if this list is empty
693      * @since 1.5
694      */
remove()695     public E remove() {
696         return removeFirst();
697     }
698 
699     /**
700      * Adds the specified element as the tail (last element) of this list.
701      *
702      * @param e the element to add
703      * @return {@code true} (as specified by {@link Queue#offer})
704      * @since 1.5
705      */
offer(E e)706     public boolean offer(E e) {
707         return add(e);
708     }
709 
710     // Deque operations
711     /**
712      * Inserts the specified element at the front of this list.
713      *
714      * @param e the element to insert
715      * @return {@code true} (as specified by {@link Deque#offerFirst})
716      * @since 1.6
717      */
offerFirst(E e)718     public boolean offerFirst(E e) {
719         addFirst(e);
720         return true;
721     }
722 
723     /**
724      * Inserts the specified element at the end of this list.
725      *
726      * @param e the element to insert
727      * @return {@code true} (as specified by {@link Deque#offerLast})
728      * @since 1.6
729      */
offerLast(E e)730     public boolean offerLast(E e) {
731         addLast(e);
732         return true;
733     }
734 
735     /**
736      * Retrieves, but does not remove, the first element of this list,
737      * or returns {@code null} if this list is empty.
738      *
739      * @return the first element of this list, or {@code null}
740      *         if this list is empty
741      * @since 1.6
742      */
peekFirst()743     public E peekFirst() {
744         final Node<E> f = first;
745         return (f == null) ? null : f.item;
746      }
747 
748     /**
749      * Retrieves, but does not remove, the last element of this list,
750      * or returns {@code null} if this list is empty.
751      *
752      * @return the last element of this list, or {@code null}
753      *         if this list is empty
754      * @since 1.6
755      */
peekLast()756     public E peekLast() {
757         final Node<E> l = last;
758         return (l == null) ? null : l.item;
759     }
760 
761     /**
762      * Retrieves and removes the first element of this list,
763      * or returns {@code null} if this list is empty.
764      *
765      * @return the first element of this list, or {@code null} if
766      *     this list is empty
767      * @since 1.6
768      */
pollFirst()769     public E pollFirst() {
770         final Node<E> f = first;
771         return (f == null) ? null : unlinkFirst(f);
772     }
773 
774     /**
775      * Retrieves and removes the last element of this list,
776      * or returns {@code null} if this list is empty.
777      *
778      * @return the last element of this list, or {@code null} if
779      *     this list is empty
780      * @since 1.6
781      */
pollLast()782     public E pollLast() {
783         final Node<E> l = last;
784         return (l == null) ? null : unlinkLast(l);
785     }
786 
787     /**
788      * Pushes an element onto the stack represented by this list.  In other
789      * words, inserts the element at the front of this list.
790      *
791      * <p>This method is equivalent to {@link #addFirst}.
792      *
793      * @param e the element to push
794      * @since 1.6
795      */
push(E e)796     public void push(E e) {
797         addFirst(e);
798     }
799 
800     /**
801      * Pops an element from the stack represented by this list.  In other
802      * words, removes and returns the first element of this list.
803      *
804      * <p>This method is equivalent to {@link #removeFirst()}.
805      *
806      * @return the element at the front of this list (which is the top
807      *         of the stack represented by this list)
808      * @throws NoSuchElementException if this list is empty
809      * @since 1.6
810      */
pop()811     public E pop() {
812         return removeFirst();
813     }
814 
815     /**
816      * Removes the first 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.
819      *
820      * @param o element to be removed from this list, if present
821      * @return {@code true} if the list contained the specified element
822      * @since 1.6
823      */
removeFirstOccurrence(Object o)824     public boolean removeFirstOccurrence(Object o) {
825         return remove(o);
826     }
827 
828     /**
829      * Removes the last occurrence of the specified element in this
830      * list (when traversing the list from head to tail).  If the list
831      * does not contain the element, it is unchanged.
832      *
833      * @param o element to be removed from this list, if present
834      * @return {@code true} if the list contained the specified element
835      * @since 1.6
836      */
removeLastOccurrence(Object o)837     public boolean removeLastOccurrence(Object o) {
838         if (o == null) {
839             for (Node<E> x = last; x != null; x = x.prev) {
840                 if (x.item == null) {
841                     unlink(x);
842                     return true;
843                 }
844             }
845         } else {
846             for (Node<E> x = last; x != null; x = x.prev) {
847                 if (o.equals(x.item)) {
848                     unlink(x);
849                     return true;
850                 }
851             }
852         }
853         return false;
854     }
855 
856     /**
857      * Returns a list-iterator of the elements in this list (in proper
858      * sequence), starting at the specified position in the list.
859      * Obeys the general contract of {@code List.listIterator(int)}.<p>
860      *
861      * The list-iterator is <i>fail-fast</i>: if the list is structurally
862      * modified at any time after the Iterator is created, in any way except
863      * through the list-iterator's own {@code remove} or {@code add}
864      * methods, the list-iterator will throw a
865      * {@code ConcurrentModificationException}.  Thus, in the face of
866      * concurrent modification, the iterator fails quickly and cleanly, rather
867      * than risking arbitrary, non-deterministic behavior at an undetermined
868      * time in the future.
869      *
870      * @param index index of the first element to be returned from the
871      *              list-iterator (by a call to {@code next})
872      * @return a ListIterator of the elements in this list (in proper
873      *         sequence), starting at the specified position in the list
874      * @throws IndexOutOfBoundsException {@inheritDoc}
875      * @see List#listIterator(int)
876      */
listIterator(int index)877     public ListIterator<E> listIterator(int index) {
878         checkPositionIndex(index);
879         return new ListItr(index);
880     }
881 
882     private class ListItr implements ListIterator<E> {
883         private Node<E> lastReturned;
884         private Node<E> next;
885         private int nextIndex;
886         private int expectedModCount = modCount;
887 
ListItr(int index)888         ListItr(int index) {
889             // assert isPositionIndex(index);
890             next = (index == size) ? null : node(index);
891             nextIndex = index;
892         }
893 
hasNext()894         public boolean hasNext() {
895             return nextIndex < size;
896         }
897 
next()898         public E next() {
899             checkForComodification();
900             if (!hasNext())
901                 throw new NoSuchElementException();
902 
903             lastReturned = next;
904             next = next.next;
905             nextIndex++;
906             return lastReturned.item;
907         }
908 
hasPrevious()909         public boolean hasPrevious() {
910             return nextIndex > 0;
911         }
912 
previous()913         public E previous() {
914             checkForComodification();
915             if (!hasPrevious())
916                 throw new NoSuchElementException();
917 
918             lastReturned = next = (next == null) ? last : next.prev;
919             nextIndex--;
920             return lastReturned.item;
921         }
922 
nextIndex()923         public int nextIndex() {
924             return nextIndex;
925         }
926 
previousIndex()927         public int previousIndex() {
928             return nextIndex - 1;
929         }
930 
remove()931         public void remove() {
932             checkForComodification();
933             if (lastReturned == null)
934                 throw new IllegalStateException();
935 
936             Node<E> lastNext = lastReturned.next;
937             unlink(lastReturned);
938             if (next == lastReturned)
939                 next = lastNext;
940             else
941                 nextIndex--;
942             lastReturned = null;
943             expectedModCount++;
944         }
945 
set(E e)946         public void set(E e) {
947             if (lastReturned == null)
948                 throw new IllegalStateException();
949             checkForComodification();
950             lastReturned.item = e;
951         }
952 
add(E e)953         public void add(E e) {
954             checkForComodification();
955             lastReturned = null;
956             if (next == null)
957                 linkLast(e);
958             else
959                 linkBefore(e, next);
960             nextIndex++;
961             expectedModCount++;
962         }
963 
forEachRemaining(Consumer<? super E> action)964         public void forEachRemaining(Consumer<? super E> action) {
965             Objects.requireNonNull(action);
966             while (modCount == expectedModCount && nextIndex < size) {
967                 action.accept(next.item);
968                 lastReturned = next;
969                 next = next.next;
970                 nextIndex++;
971             }
972             checkForComodification();
973         }
974 
checkForComodification()975         final void checkForComodification() {
976             if (modCount != expectedModCount)
977                 throw new ConcurrentModificationException();
978         }
979     }
980 
981     private static class Node<E> {
982         E item;
983         Node<E> next;
984         Node<E> prev;
985 
Node(Node<E> prev, E element, Node<E> next)986         Node(Node<E> prev, E element, Node<E> next) {
987             this.item = element;
988             this.next = next;
989             this.prev = prev;
990         }
991     }
992 
993     /**
994      * @since 1.6
995      */
descendingIterator()996     public Iterator<E> descendingIterator() {
997         return new DescendingIterator();
998     }
999 
1000     /**
1001      * Adapter to provide descending iterators via ListItr.previous
1002      */
1003     private class DescendingIterator implements Iterator<E> {
1004         private final ListItr itr = new ListItr(size());
hasNext()1005         public boolean hasNext() {
1006             return itr.hasPrevious();
1007         }
next()1008         public E next() {
1009             return itr.previous();
1010         }
remove()1011         public void remove() {
1012             itr.remove();
1013         }
1014     }
1015 
1016     @SuppressWarnings("unchecked")
superClone()1017     private LinkedList<E> superClone() {
1018         try {
1019             return (LinkedList<E>) super.clone();
1020         } catch (CloneNotSupportedException e) {
1021             throw new InternalError(e);
1022         }
1023     }
1024 
1025     /**
1026      * Returns a shallow copy of this {@code LinkedList}. (The elements
1027      * themselves are not cloned.)
1028      *
1029      * @return a shallow copy of this {@code LinkedList} instance
1030      */
clone()1031     public Object clone() {
1032         LinkedList<E> clone = superClone();
1033 
1034         // Put clone into "virgin" state
1035         clone.first = clone.last = null;
1036         clone.size = 0;
1037         clone.modCount = 0;
1038 
1039         // Initialize clone with our elements
1040         for (Node<E> x = first; x != null; x = x.next)
1041             clone.add(x.item);
1042 
1043         return clone;
1044     }
1045 
1046     /**
1047      * Returns an array containing all of the elements in this list
1048      * in proper sequence (from first to last element).
1049      *
1050      * <p>The returned array will be "safe" in that no references to it are
1051      * maintained by this list.  (In other words, this method must allocate
1052      * a new array).  The caller is thus free to modify the returned array.
1053      *
1054      * <p>This method acts as bridge between array-based and collection-based
1055      * APIs.
1056      *
1057      * @return an array containing all of the elements in this list
1058      *         in proper sequence
1059      */
toArray()1060     public Object[] toArray() {
1061         Object[] result = new Object[size];
1062         int i = 0;
1063         for (Node<E> x = first; x != null; x = x.next)
1064             result[i++] = x.item;
1065         return result;
1066     }
1067 
1068     /**
1069      * Returns an array containing all of the elements in this list in
1070      * proper sequence (from first to last element); the runtime type of
1071      * the returned array is that of the specified array.  If the list fits
1072      * in the specified array, it is returned therein.  Otherwise, a new
1073      * array is allocated with the runtime type of the specified array and
1074      * the size of this list.
1075      *
1076      * <p>If the list fits in the specified array with room to spare (i.e.,
1077      * the array has more elements than the list), the element in the array
1078      * immediately following the end of the list is set to {@code null}.
1079      * (This is useful in determining the length of the list <i>only</i> if
1080      * the caller knows that the list does not contain any null elements.)
1081      *
1082      * <p>Like the {@link #toArray()} method, this method acts as bridge between
1083      * array-based and collection-based APIs.  Further, this method allows
1084      * precise control over the runtime type of the output array, and may,
1085      * under certain circumstances, be used to save allocation costs.
1086      *
1087      * <p>Suppose {@code x} is a list known to contain only strings.
1088      * The following code can be used to dump the list into a newly
1089      * allocated array of {@code String}:
1090      *
1091      * <pre>
1092      *     String[] y = x.toArray(new String[0]);</pre>
1093      *
1094      * Note that {@code toArray(new Object[0])} is identical in function to
1095      * {@code toArray()}.
1096      *
1097      * @param a the array into which the elements of the list are to
1098      *          be stored, if it is big enough; otherwise, a new array of the
1099      *          same runtime type is allocated for this purpose.
1100      * @return an array containing the elements of the list
1101      * @throws ArrayStoreException if the runtime type of the specified array
1102      *         is not a supertype of the runtime type of every element in
1103      *         this list
1104      * @throws NullPointerException if the specified array is null
1105      */
1106     @SuppressWarnings("unchecked")
toArray(T[] a)1107     public <T> T[] toArray(T[] a) {
1108         if (a.length < size)
1109             a = (T[])java.lang.reflect.Array.newInstance(
1110                                 a.getClass().getComponentType(), size);
1111         int i = 0;
1112         Object[] result = a;
1113         for (Node<E> x = first; x != null; x = x.next)
1114             result[i++] = x.item;
1115 
1116         if (a.length > size)
1117             a[size] = null;
1118 
1119         return a;
1120     }
1121 
1122     @java.io.Serial
1123     private static final long serialVersionUID = 876323262645176354L;
1124 
1125     /**
1126      * Saves the state of this {@code LinkedList} instance to a stream
1127      * (that is, serializes it).
1128      *
1129      * @serialData The size of the list (the number of elements it
1130      *             contains) is emitted (int), followed by all of its
1131      *             elements (each an Object) in the proper order.
1132      */
1133     @java.io.Serial
writeObject(java.io.ObjectOutputStream s)1134     private void writeObject(java.io.ObjectOutputStream s)
1135         throws java.io.IOException {
1136         // Write out any hidden serialization magic
1137         s.defaultWriteObject();
1138 
1139         // Write out size
1140         s.writeInt(size);
1141 
1142         // Write out all elements in the proper order.
1143         for (Node<E> x = first; x != null; x = x.next)
1144             s.writeObject(x.item);
1145     }
1146 
1147     /**
1148      * Reconstitutes this {@code LinkedList} instance from a stream
1149      * (that is, deserializes it).
1150      */
1151     @SuppressWarnings("unchecked")
1152     @java.io.Serial
readObject(java.io.ObjectInputStream s)1153     private void readObject(java.io.ObjectInputStream s)
1154         throws java.io.IOException, ClassNotFoundException {
1155         // Read in any hidden serialization magic
1156         s.defaultReadObject();
1157 
1158         // Read in size
1159         int size = s.readInt();
1160 
1161         // Read in all elements in the proper order.
1162         for (int i = 0; i < size; i++)
1163             linkLast((E)s.readObject());
1164     }
1165 
1166     /**
1167      * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
1168      * and <em>fail-fast</em> {@link Spliterator} over the elements in this
1169      * list.
1170      *
1171      * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
1172      * {@link Spliterator#ORDERED}.  Overriding implementations should document
1173      * the reporting of additional characteristic values.
1174      *
1175      * @implNote
1176      * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}
1177      * and implements {@code trySplit} to permit limited parallelism..
1178      *
1179      * @return a {@code Spliterator} over the elements in this list
1180      * @since 1.8
1181      */
1182     @Override
spliterator()1183     public Spliterator<E> spliterator() {
1184         return new LLSpliterator<>(this, -1, 0);
1185     }
1186 
1187     /** A customized variant of Spliterators.IteratorSpliterator */
1188     static final class LLSpliterator<E> implements Spliterator<E> {
1189         static final int BATCH_UNIT = 1 << 10;  // batch array size increment
1190         static final int MAX_BATCH = 1 << 25;  // max batch array size;
1191         final LinkedList<E> list; // null OK unless traversed
1192         Node<E> current;      // current node; null until initialized
1193         int est;              // size estimate; -1 until first needed
1194         int expectedModCount; // initialized when est set
1195         int batch;            // batch size for splits
1196 
LLSpliterator(LinkedList<E> list, int est, int expectedModCount)1197         LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
1198             this.list = list;
1199             this.est = est;
1200             this.expectedModCount = expectedModCount;
1201         }
1202 
getEst()1203         final int getEst() {
1204             int s; // force initialization
1205             final LinkedList<E> lst;
1206             if ((s = est) < 0) {
1207                 if ((lst = list) == null)
1208                     s = est = 0;
1209                 else {
1210                     expectedModCount = lst.modCount;
1211                     current = lst.first;
1212                     s = est = lst.size;
1213                 }
1214             }
1215             return s;
1216         }
1217 
estimateSize()1218         public long estimateSize() { return (long) getEst(); }
1219 
trySplit()1220         public Spliterator<E> trySplit() {
1221             Node<E> p;
1222             int s = getEst();
1223             if (s > 1 && (p = current) != null) {
1224                 int n = batch + BATCH_UNIT;
1225                 if (n > s)
1226                     n = s;
1227                 if (n > MAX_BATCH)
1228                     n = MAX_BATCH;
1229                 Object[] a = new Object[n];
1230                 int j = 0;
1231                 do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
1232                 current = p;
1233                 batch = j;
1234                 est = s - j;
1235                 return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
1236             }
1237             return null;
1238         }
1239 
forEachRemaining(Consumer<? super E> action)1240         public void forEachRemaining(Consumer<? super E> action) {
1241             Node<E> p; int n;
1242             if (action == null) throw new NullPointerException();
1243             if ((n = getEst()) > 0 && (p = current) != null) {
1244                 current = null;
1245                 est = 0;
1246                 do {
1247                     E e = p.item;
1248                     p = p.next;
1249                     action.accept(e);
1250                 } while (p != null && --n > 0);
1251             }
1252             if (list.modCount != expectedModCount)
1253                 throw new ConcurrentModificationException();
1254         }
1255 
tryAdvance(Consumer<? super E> action)1256         public boolean tryAdvance(Consumer<? super E> action) {
1257             Node<E> p;
1258             if (action == null) throw new NullPointerException();
1259             if (getEst() > 0 && (p = current) != null) {
1260                 --est;
1261                 E e = p.item;
1262                 current = p.next;
1263                 action.accept(e);
1264                 if (list.modCount != expectedModCount)
1265                     throw new ConcurrentModificationException();
1266                 return true;
1267             }
1268             return false;
1269         }
1270 
characteristics()1271         public int characteristics() {
1272             return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
1273         }
1274     }
1275 
1276     /**
1277      * {@inheritDoc}
1278      * <p>
1279      * Modifications to the reversed view are permitted and will be propagated to this list.
1280      * In addition, modifications to this list will be visible in the reversed view.
1281      *
1282      * @return {@inheritDoc}
1283      * @since 21
1284      */
reversed()1285     public LinkedList<E> reversed() {
1286         return new ReverseOrderLinkedListView<>(this, super.reversed(), Deque.super.reversed());
1287     }
1288 
1289     // all operations are delegated to the reverse-ordered views.
1290     // TODO audit all overridden methods
1291     @SuppressWarnings("serial")
1292     static class ReverseOrderLinkedListView<E> extends LinkedList<E> implements java.io.Externalizable {
1293         final LinkedList<E> list;
1294         final List<E> rlist;
1295         final Deque<E> rdeque;
1296 
ReverseOrderLinkedListView(LinkedList<E> list, List<E> rlist, Deque<E> rdeque)1297         ReverseOrderLinkedListView(LinkedList<E> list, List<E> rlist, Deque<E> rdeque) {
1298             this.list = list;
1299             this.rlist = rlist;
1300             this.rdeque = rdeque;
1301         }
1302 
toString()1303         public String toString() {
1304             return rlist.toString();
1305         }
1306 
retainAll(Collection<?> c)1307         public boolean retainAll(Collection<?> c) {
1308             return rlist.retainAll(c);
1309         }
1310 
removeAll(Collection<?> c)1311         public boolean removeAll(Collection<?> c) {
1312             return rlist.removeAll(c);
1313         }
1314 
containsAll(Collection<?> c)1315         public boolean containsAll(Collection<?> c) {
1316             return rlist.containsAll(c);
1317         }
1318 
isEmpty()1319         public boolean isEmpty() {
1320             return rlist.isEmpty();
1321         }
1322 
parallelStream()1323         public Stream<E> parallelStream() {
1324             return rlist.parallelStream();
1325         }
1326 
stream()1327         public Stream<E> stream() {
1328             return rlist.stream();
1329         }
1330 
removeIf(Predicate<? super E> filter)1331         public boolean removeIf(Predicate<? super E> filter) {
1332             return rlist.removeIf(filter);
1333         }
1334 
toArray(IntFunction<T[]> generator)1335         public <T> T[] toArray(IntFunction<T[]> generator) {
1336             return rlist.toArray(generator);
1337         }
1338 
forEach(Consumer<? super E> action)1339         public void forEach(Consumer<? super E> action) {
1340             rlist.forEach(action);
1341         }
1342 
iterator()1343         public Iterator<E> iterator() {
1344             return rlist.iterator();
1345         }
1346 
hashCode()1347         public int hashCode() {
1348             return rlist.hashCode();
1349         }
1350 
equals(Object o)1351         public boolean equals(Object o) {
1352             return rlist.equals(o);
1353         }
1354 
subList(int fromIndex, int toIndex)1355         public List<E> subList(int fromIndex, int toIndex) {
1356             return rlist.subList(fromIndex, toIndex);
1357         }
1358 
listIterator()1359         public ListIterator<E> listIterator() {
1360             return rlist.listIterator();
1361         }
1362 
sort(Comparator<? super E> c)1363         public void sort(Comparator<? super E> c) {
1364             rlist.sort(c);
1365         }
1366 
replaceAll(UnaryOperator<E> operator)1367         public void replaceAll(UnaryOperator<E> operator) {
1368             rlist.replaceAll(operator);
1369         }
1370 
reversed()1371         public LinkedList<E> reversed() {
1372             return list;
1373         }
1374 
spliterator()1375         public Spliterator<E> spliterator() {
1376             return rlist.spliterator();
1377         }
1378 
toArray(T[] a)1379         public <T> T[] toArray(T[] a) {
1380             return rlist.toArray(a);
1381         }
1382 
toArray()1383         public Object[] toArray() {
1384             return rlist.toArray();
1385         }
1386 
descendingIterator()1387         public Iterator<E> descendingIterator() {
1388             return rdeque.descendingIterator();
1389         }
1390 
listIterator(int index)1391         public ListIterator<E> listIterator(int index) {
1392             return rlist.listIterator(index);
1393         }
1394 
removeLastOccurrence(Object o)1395         public boolean removeLastOccurrence(Object o) {
1396             return rdeque.removeLastOccurrence(o);
1397         }
1398 
removeFirstOccurrence(Object o)1399         public boolean removeFirstOccurrence(Object o) {
1400             return rdeque.removeFirstOccurrence(o);
1401         }
1402 
pop()1403         public E pop() {
1404             return rdeque.pop();
1405         }
1406 
push(E e)1407         public void push(E e) {
1408             rdeque.push(e);
1409         }
1410 
pollLast()1411         public E pollLast() {
1412             return rdeque.pollLast();
1413         }
1414 
pollFirst()1415         public E pollFirst() {
1416             return rdeque.pollFirst();
1417         }
1418 
peekLast()1419         public E peekLast() {
1420             return rdeque.peekLast();
1421         }
1422 
peekFirst()1423         public E peekFirst() {
1424             return rdeque.peekFirst();
1425         }
1426 
offerLast(E e)1427         public boolean offerLast(E e) {
1428             return rdeque.offerLast(e);
1429         }
1430 
offerFirst(E e)1431         public boolean offerFirst(E e) {
1432             return rdeque.offerFirst(e);
1433         }
1434 
offer(E e)1435         public boolean offer(E e) {
1436             return rdeque.offer(e);
1437         }
1438 
remove()1439         public E remove() {
1440             return rdeque.remove();
1441         }
1442 
poll()1443         public E poll() {
1444             return rdeque.poll();
1445         }
1446 
element()1447         public E element() {
1448             return rdeque.element();
1449         }
1450 
peek()1451         public E peek() {
1452             return rdeque.peek();
1453         }
1454 
lastIndexOf(Object o)1455         public int lastIndexOf(Object o) {
1456             return rlist.lastIndexOf(o);
1457         }
1458 
indexOf(Object o)1459         public int indexOf(Object o) {
1460             return rlist.indexOf(o);
1461         }
1462 
remove(int index)1463         public E remove(int index) {
1464             return rlist.remove(index);
1465         }
1466 
add(int index, E element)1467         public void add(int index, E element) {
1468             rlist.add(index, element);
1469         }
1470 
set(int index, E element)1471         public E set(int index, E element) {
1472             return rlist.set(index, element);
1473         }
1474 
get(int index)1475         public E get(int index) {
1476             return rlist.get(index);
1477         }
1478 
clear()1479         public void clear() {
1480             rlist.clear();
1481         }
1482 
addAll(int index, Collection<? extends E> c)1483         public boolean addAll(int index, Collection<? extends E> c) {
1484             return rlist.addAll(index, c);
1485         }
1486 
addAll(Collection<? extends E> c)1487         public boolean addAll(Collection<? extends E> c) {
1488             return rlist.addAll(c);
1489         }
1490 
remove(Object o)1491         public boolean remove(Object o) {
1492             return rlist.remove(o);
1493         }
1494 
add(E e)1495         public boolean add(E e) {
1496             return rlist.add(e);
1497         }
1498 
size()1499         public int size() {
1500             return rlist.size();
1501         }
1502 
contains(Object o)1503         public boolean contains(Object o) {
1504             return rlist.contains(o);
1505         }
1506 
addLast(E e)1507         public void addLast(E e) {
1508             rdeque.addLast(e);
1509         }
1510 
addFirst(E e)1511         public void addFirst(E e) {
1512             rdeque.addFirst(e);
1513         }
1514 
removeLast()1515         public E removeLast() {
1516             return rdeque.removeLast();
1517         }
1518 
removeFirst()1519         public E removeFirst() {
1520             return rdeque.removeFirst();
1521         }
1522 
getLast()1523         public E getLast() {
1524             return rdeque.getLast();
1525         }
1526 
getFirst()1527         public E getFirst() {
1528             return rdeque.getFirst();
1529         }
1530 
readExternal(ObjectInput in)1531         public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
1532             throw new java.io.InvalidObjectException("not serializable");
1533         }
1534 
writeExternal(ObjectOutput out)1535         public void writeExternal(ObjectOutput out) throws IOException {
1536             throw new java.io.InvalidObjectException("not serializable");
1537         }
1538     }
1539 }
1540