您好,登錄后才能下訂單哦!
這篇文章主要介紹“LinkedList是什么”,在日常操作中,相信很多人在LinkedList是什么問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對(duì)大家解答”LinkedList是什么”的疑惑有所幫助!接下來,請(qǐng)跟著小編一起來學(xué)習(xí)吧!
LinkedList是一個(gè)鏈表集合。
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
可以發(fā)現(xiàn)LinkedList沒有實(shí)現(xiàn)RandomAccess接口,意味著不可以使用for(int i = 0; i < size; i++)進(jìn)行遍歷數(shù)據(jù)
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; } }
通過節(jié)點(diǎn)的數(shù)據(jù)結(jié)構(gòu),可以看出來LinkedList
是一個(gè)雙向鏈表。鏈表的特性是方便插入和刪除界面。
/** * 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
是提供的兩個(gè)對(duì)于邊界檢查的方法, 通過代碼發(fā)現(xiàn),一個(gè)是[0, size), 一個(gè)是[0,size], 范圍是不一樣的,因?yàn)樗饕秊閟ize的位置是一個(gè)可插入位,但不是現(xiàn)有的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,算法采用了二分法。雖然在時(shí)間復(fù)雜度上還是o(n), 但實(shí)際計(jì)算時(shí)確實(shí)節(jié)省了1/2的時(shí)間。
peek() 直接返回頭節(jié)點(diǎn)
poll() 返回頭節(jié)點(diǎn),并在鏈表中刪除
到此,關(guān)于“LinkedList是什么”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。