LinkedList是一個鏈表集合。
public class LinkedList<E>
extends AbstractSequentialList<E>
implements List<E>, Deque<E>, Cloneable, java.io.Serializable
可以發現LinkedList沒有實現RandomAccess接口,意味著不可以使用for(int i = 0; i < size; i++)進行遍歷數據
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;
}
}
通過節點的數據結構,可以看出來LinkedList
是一個雙向鏈表。鏈表的特性是方便插入和刪除界面。
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
/**
* Tells if the argument is the index of a valid position for an
* iterator or an add operation.
*/
private boolean isPositionIndex(int index) {
return index >= 0 && index <= size;
}
isElementIndex
, isPositionIndex
是提供的兩個對于邊界檢查的方法, 通過代碼發現,一個是[0, size), 一個是[0,size], 范圍是不一樣的,因為索引為size的位置是一個可插入位,但不是現有的Element位。
/**
* Returns the (non-null) Node at the specified element index.
*/
Node<E> node(int index) {
// assert isElementIndex(index);
// 采用二分法遍歷鏈表
if (index < (size >> 1)) {
Node<E> x = first;
for (int i = 0; i < index; i++)
x = x.next;
return x;
} else {
Node<E> x = last;
for (int i = size - 1; i > index; i--)
x = x.prev;
return x;
}
}
獲取指定index的element,算法采用了二分法。雖然在時間復雜度上還是o(n), 但實際計算時確實節省了1/2的時間。
peek() 直接返回頭節點
poll() 返回頭節點,并在鏈表中刪除