1. Data structure--linkedlist Source Summary
Public classLinkedlist<e>extendsAbstractsequentiallist<e>ImplementsList<e>, deque<e>, cloneable, java.io.serializable{transient intSize = 0; /*** Pointer to first node. * Invariant: (first = = NULL && last = = null) | | * (First.prev = = NULL && First.item! = null)*/ transientNode<e>First ; /*** Pointer to the last node. * Invariant: (first = = NULL && last = = null) | | * (Last.next = = NULL && Last.item! = null)*/ transientNode<e>Last ;}
LinkedList the most important three properties, Size,first,last, can be seen, LinkedList is a doubly linked list of data structure.
Private Static class Node<e> { E item; Node<E> next; Node<E> prev; Node (node<E> prev, E element, node<e> next) { this. Item= element; this. Next = next; this. prev = prev; } }
Node nodes contain a reference to the item element, prev Previous node, and next next node.
2 LinkedList adjustment of the underlying data
Add method
/*** Appends the specified element to the end of this list. * * <p>this method is equivalent to {@link#addLast}. * * @parame element to is appended to the this list *@return {@codetrue} (as specified by {@linkCollection#add}) */ Public BooleanAdd (e e) {linklast (e); return true; }
/**
* Links e as last element.
*/
void Linklast (e e) {
final node<e> l = last ;
final node<e> newNode = new Node<> (L, E, null);
Last = newNode;
if (l = = null)
First = newNode;
Else
L.next = newNode;
size++;
modcount++;
}
As can be seen from the source code, the Add method calls the Linklast method directly, the method 1. Instantiate a node, append to the end of the list, 2 adjust the previous
The next node of the node is applied as a new node. 3 Modify last for the new node node. As a result, LinkedList's new and deleted operations are significantly more efficient.
Get method
/*** Returns The element at the specified position of this list. * * @paramIndex Index of the element to return *@returnThe element at the specified position in this list *@throwsindexoutofboundsexception {@inheritDoc} */ PublicE Get (intindex) {Checkelementindex (index); returnnode (index). Item; } /*** Returns the (non-null) Node at the specified element index. */Node<E> node (intindex) { //assert Iselementindex (index); if(Index < (size >> 1) ) {Node<E> x =First ; for(inti = 0; I < index; i++) x=X.next; returnx; } Else{Node<E> x =Last ; for(inti = size-1; i > Index; i--) x=X.prev; returnx; } }
The Get method first checks whether the index is out of bounds (return index >= 0 && index <= size; ), the second determines whether the index is greater than half of the size in terms of the dichotomy, and if it is greater then it is retrieved from backward, less than the previous search.
The underlying data structure of Java's LinkedList