For more information, refer to my personal blog: a cheap Dream
LinkedList Introduction LinkedList is a doubly linked list that inherits from the Abstractsequentiallist. It can also be manipulated as a stack, a queue, or a two-terminal queue. LinkedList implements the List interface and can perform queue operations. LinkedList implements the Deque interface, that is, LinkedList can be used as a two-terminal queue. ArrayList the bottom layer is supported by arrays, and LinkedList is implemented by a two-way list, where each object contains data and contains references to the previous and last elements in the list. linkedlist Traversal Mode
LinkedList has the following traversal methods: iterator traversal
Iterator<integer> iterator = Linkedlist.iterator ();
while (Iterator.hasnext ()) {
iterator.next ();
}
For Loop get () traversal
for (int i = 0; i < linkedlist.size (); i++) {
linkedlist.get (i);
}
foreach Loop traversal
for (Integer i:linkedlist);
traversing through Pollfirst () or polllast ()
while (Linkedlist.size ()!= 0) {
linkedlist.pollfirst ();
}
traversing through Removefirst () or removelast ()
while (Linkedlist.size ()!= 0) {
linkedlist.removefirst ();
}
Efficiency Test
To test the efficiency of several traversal methods, some of the code is as follows:
/************************** traversal Operation ************************/System.out.println ("----------------------------------
-------");
Linkedlist.clear ();
for (int i = 0; i < 100000 i++) {linkedlist.add (i);}//iterator traversal long start = System.currenttimemillis ();
Iterator<integer> iterator = Linkedlist.iterator ();
while (Iterator.hasnext ()) {Iterator.next ();} Long end = System.currenttimemillis ();
System.out.println ("Iterator:" + (End-start) + "MS");
Sequential traversal (random traversal) start = System.currenttimemillis ();
for (int i = 0; i < linkedlist.size (); i++) {linkedlist.get (i);} end = System.currenttimemillis ();
System.out.println ("for:" + (End-start) + "MS");
Another for loop traversal start = System.currenttimemillis ();
for (Integer i:linkedlist);
End = System.currenttimemillis ();
System.out.println ("For2:" + (End-start) + "MS");
Traverse LinkedList linkedlist<integer> Temp1 = new linkedlist<> () by Pollfirst () or polllast ();
Temp1.addall (LinkedList);
Start = System.currenttimemillis (); WHile (temp1.size ()!= 0) {Temp1.pollfirst ();} end = System.currenttimemillis ();
System.out.println ("Pollfirst () or Polllast ():" + (End-start) + "MS");
Traverse LinkedList linkedlist<integer> temp2 = new linkedlist<> () by Removefirst () or removelast ();
Temp2.addall (LinkedList);
Start = System.currenttimemillis ();
while (Temp2.size ()!= 0) {Temp2.removefirst ();} end = System.currenttimemillis (); System.out.println ("Removefirst () or Removelast ():" + (End-start) + "MS");
Output:
-----------------------------------------
iterator:17 Ms
for:8419 Ms
for2:12 Ms
Pollfirst () or Polllast (): Ms
Removefirst () or Removelast (): MS
As can be seen from the test results, the use of Removefirst () or Removelast () is the most efficient when traversing linkedlist, and the For Loop get () is the least efficient and should be avoided in this way. It should be noted that when using Pollfirst () or polllast () or Removefirst () or removelast () traversal, the original data is deleted, and the first or third method should be used for simple reading. LinkedList Sample
/** * @author Gongchuangsu * @since 2016.05.11/import java.util.Iterator;
Import java.util.LinkedList; public class Linkedlistdemo {public static void main (string[] srgs) {linkedlist<integer> LinkedList = n
EW linkedlist<> (); /************************** Basic Operation ************************/Linkedlist.addfirst (0); Add elements to the beginning of the list linkedlist.add (1); add Element Linkedlist.add (2,2) at the end of the list; Adds an element Linkedlist.addlast (3) at the specified location;
Add elements to the end of the list System.out.println ("LinkedList:" + LinkedList); System.out.println ("GetFirst ():" + Linkedlist.getfirst ()); Returns the first element of this list System.out.println ("GetLast ():" + linkedlist.getlast ()); Returns the last element of this list System.out.println ("Removefirst ():" + Linkedlist.removefirst ()); Remove and return the first element of this list System.out.println ("Removelast ():" + linkedlist.removelast ()); Remove and return the last element of this list System.out.println ("After remove:" + LinKedlist); System.out.println ("contains (1) is:" + linkedlist.contains (1)); Determines whether this list contains the specified element and, if so, returns True System.out.println ("size is:" + linkedlist.size ()); Returns the number of elements in this list/************************** position access Operation ************************/System.out.println ("----------
-------------------------------"); Linkedlist.set (1, 3);
Replaces the element at the specified position in this list with the specified element System.out.println ("After set (1, 3):" + LinkedList); System.out.println ("Get (1):" + linkedlist.get (1)); Returns the element at the specified position in this list/************************** search operation ************************/System.out.println ("---
--------------------------------------");
Linkedlist.add (3); System.out.println ("IndexOf (3):" + linkedlist.indexof (3));
Returns the index System.out.println ("LastIndexOf (3):" + linkedlist.lastindexof (3)) for the first occurrence of the specified element in this list;//returns the index of the last occurrence of the specified element in this list /*****Queue Operation ************************/System.out.println ("------------------------------------
-----"); System.out.println ("Peek ():" + Linkedlist.peek ()); Gets the header System.out.println ("Element ():" + linkedlist.element ()) that does not remove this list. Gets the header linkedlist.poll () without removing the list;
Gets and removes the header System.out.println of this list ("after poll ():" + LinkedList);
Linkedlist.remove (); System.out.println ("After remove ():" + LinkedList);
Gets and removes the header Linkedlist.offer (4) of this list; System.out.println ("After offer (4):" + LinkedList); Adds the specified element to the end of this list/************************** deque operation ************************/System.out.println ("-
----------------------------------------"); Linkedlist.offerfirst (2); Inserts the specified element System.out.println at the beginning of this list ("After Offerfirst (2):" + LinkedlisT); Linkedlist.offerlast (5);
Inserts the specified element System.out.println at the end of this list ("After Offerlast (5):" + LinkedList); System.out.println ("Peekfirst ():" + Linkedlist.peekfirst ()); Gets but does not remove the first element of this list System.out.println ("Peeklast ():" + linkedlist.peeklast ()); Gets but not removes the first element of this list linkedlist.pollfirst ();
Gets and removes the first element of this list System.out.println ("After Pollfirst ():" + LinkedList); Linkedlist.polllast ();
Gets and removes the last element of this list System.out.println ("After Polllast ():" + LinkedList); Linkedlist.push (2);
Pushes an element into the stack represented by this list (inserted into the head of the list) System.out.println ("After push (2):" + LinkedList); Linkedlist.pop ();
POPs an element from the stack represented by this list (gets and removes the first element of the list) System.out.println ("After pop ():" + LinkedList); LinkEdlist.add (3); Linkedlist.removefirstoccurrence (3);
Removes the first occurrence of the specified element from the list (from head to tail traversal list) System.out.println ("After Removefirstoccurrence (3):" + LinkedList); Linkedlist.removelastoccurrence (3);
Removes the last occurrence of the specified element from the list (from head to tail traversal list) System.out.println ("After Removefirstoccurrence (3):" + LinkedList); /************************** traversal Operation ************************/System.out.println ("---------------------------------
--------");
Linkedlist.clear ();
for (int i = 0; i < 100000 i++) {linkedlist.add (i);
}//iterator traversal long start = System.currenttimemillis ();
Iterator<integer> iterator = Linkedlist.iterator ();
while (Iterator.hasnext ()) {iterator.next ();
Long end = System.currenttimemillis ();
System.out.println ("Iterator:" + (End-start) + "MS"); Sequential traversal (random traversal) start = SystEm.currenttimemillis ();
for (int i = 0; i < linkedlist.size (); i++) {linkedlist.get (i);
End = System.currenttimemillis ();
System.out.println ("for:" + (End-start) + "MS");
Another for loop traversal start = System.currenttimemillis ();
for (Integer i:linkedlist);
End = System.currenttimemillis ();
System.out.println ("For2:" + (End-start) + "MS");
Traverse LinkedList linkedlist<integer> Temp1 = new linkedlist<> () by Pollfirst () or polllast ();
Temp1.addall (LinkedList);
Start = System.currenttimemillis ();
while (Temp1.size ()!= 0) {Temp1.pollfirst ();
End = System.currenttimemillis ();
System.out.println ("Pollfirst () or Polllast ():" + (End-start) + "MS");
Traverse LinkedList linkedlist<integer> temp2 = new linkedlist<> () by Removefirst () or removelast ();
Temp2.addall (LinkedList); Start = System.cuRrenttimemillis ();
while (Temp2.size ()!= 0) {Temp2.removefirst ();
End = System.currenttimemillis ();
System.out.println ("Removefirst () or Removelast ():" + (End-start) + "MS"); }/**output LinkedList: [0, 1, 2, 3] GetFirst (): 0 getlast (): 3 Removefirst (): 0 removelast (): 3 after remove:[1, 2] con Tains (1) is:true size Is:2-----------------------------------------after set (1, 3): [1, 3] Get (1): 3----------------- ------------------------indexOf (3): 1 LastIndexOf (3): 2-----------------------------------------Peek (): 1 element () : 1 after the poll (): [3, 3] after the Remove (): [3] After the offer (4): [3, 4]-----------------------------------------after Offerfirs T (2): [2, 3, 4] after Offerlast (5): [2, 3, 4, 5] Peekfirst (): 2 Peeklast (): 5 after Pollfirst (): [3, 4, 5] after Polllast (): [
3, 4] after push (2): [2, 3, 4] after POPs (): [3, 4] after removefirstoccurrence (3): [4, 3] after removefirstoccurrence (3): [4] -----------------------------------------IteratOr:17 ms for:8419 ms For2:12 ms Pollfirst () or Polllast (): Ms Removefirst () or Removelast (): MS * * Comparison of LinkedList and ArrayListThe insertion element is very fast in the LinkedList, and the ArrayList is slow in LinkedList, and random access in ArrayList is very slow.
LinkedList Source Analysis
Package java.util; public class Linkedlist<e> extends abstractsequentiallist<e> implements List<e>, Deque<e>
Cloneable, java.io.Serializable {transient int size = 0;
The first node transient node<e>;
The last node transient node<e>; Constructs an empty list public LinkedList () {}//Constructs a list containing the elements in the specified Collection, and/or the elements in the order in which they are returned by their Collection iterators p
Ublic LinkedList (collection< extends e> c) {this ();
AddAll (c);
//Returns the first element of this list public E GetFirst () {final node<e> f = i;
if (f = = null) throw new Nosuchelementexception ();
return f.item;
//Returns the last element of this list public E GetLast () {final node<e> L = previous;
if (L = = null) throw new Nosuchelementexception ();
return l.item;
}//Remove and return the first element of this list public E Removefirst () {final node<e> f = i; if (f = =NULL) throw new Nosuchelementexception ();
Return Unlinkfirst (f);
//Remove and return the last element of this list public E Removelast () {final node<e> L = previous;
if (L = = null) throw new Nosuchelementexception ();
Return Unlinklast (L);
///Inserts the specified element at the beginning of this list public void AddFirst (e) {Linkfirst (e);
///Add the specified element to the end of this list public void AddLast (e) {linklast (e);
//Determine if this list contains the specified element, and if so, returns True public Boolean contains (Object o) {return indexOf (o)!=-1;
//Returns the number of elements in this list public int size () {return size;
///Add the specified element to the end of this list public boolean add (e) {linklast (e);
return true;
///Removes the first occurrence of the specified element from this list (returns False if there is a return true) public boolean remove (Object o) {if (o = = null) { for (node<e> x = i x!= null; x = X.next) {if (X.item = = null) {unlink (
x); REturn true; }} else {for (node<e> x = i x!= null; x = X.next) {if (O).
Equals (X.item)) {unlink (x);
return true;
}} return false; ///Add all elements in the specified collection to the end of this list,//order is the order in which the collection iterator returns the sequence of these elements public boolean addall (COLLECTION< E
Xtends e> c) {return AddAll (size, c);
///Inserts the list of all elements in the specified collection from the specified location public boolean addall (int index, COLLECTION<? extends e> c) {
Checkpositionindex (index)//check the range of index object[] a = C.toarray ();
int numnew = A.length;
if (numnew = 0)//If C is empty, returns false return false;
Node<e> pred, SUCC;
if (index = = size) {//the insertion position is the end of the list succ = null;
Pred = Last; else {succ = node (index); The insertion position is not at the end of the list pred =Succ.prev;
///add element to pred end for (Object o:a) {@SuppressWarnings ("unchecked") E = (e) o;
node<e> NewNode = new Node<> (pred, E, NULL);
if (pred = = null)-NewNode;
else Pred.next = NewNode;
pred = NewNode;
///Consolidate the remaining elements together if (succ = null) {last = pred;
else {pred.next = SUCC;
Succ.prev = pred;
Size + = Numnew;
modcount++;
return true;
///Remove all elements from this list public void clear () {//clearing all of the links between nodes is "unnecessary", but: -Helps a generational GC if the discarded nodes inhabit/more than one generation// Sure to free memory even if there are a reachable iterator for (node<e> x = i x!= null;)
{node<e> next = X.next; X.item= NULL;
X.next = null;
X.prev = null;
x = Next;
The A = last = null;
size = 0;
modcount++;
/********************** position Access Operation **************************///Returns the element public E get (int index) {at the specified position in this list
Checkelementindex (index);
Return node (index). Item;
//Replace the element at the specified position in this list with the specified element public E set (int index, E element) {Checkelementindex (index);
Node<e> x = node (index);
E oldval = X.item;
X.item = element;
return oldval;
Insert the specified element public void Add (int index, E element) {Checkpositionindex (index) at the location specified in this list;
if (index = = size)//insert to end linklast (element);
else Linkbefore (element, node (index));
//Remove element public E Remove (int index) {checkelementindex (index) at the specified location in this list;
Return unlink (node (index)); }//(Package access rights) returns the node (not NULL) at the specified location node<e&Gt
Node (int index) {//Assert Iselementindex (index); Depending on whether the specified position is on the left or the right half,//to determine whether to search for a forward or reverse lookup 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; The/********************** search operation **************************///Returns the index of the specified element that first appears in this list,//If the element is not included in this list,
Returns-1 public int indexOf (Object o) {int index = 0;
if (o = = null) {for (node<e> x = i x!= null; x = X.next) {if (X.item = = null)
return index;
index++; } else {for (node<e> x = i x!= null; x = X.next) {if (O.equals (X.item) ) returnIndex
index++;
}} return-1;
//Returns the index of the last occurrence of the specified element in this list,//If the element is not included in this list, returns-1 public int lastindexof (Object o) {int index = size;
if (o = = null) {for (node<e> x = last; x!= null; x = X.prev) {index--;