日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

数据结构特性解析 (四)LinkedList

發布時間:2025/3/21 40 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数据结构特性解析 (四)LinkedList 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

描述

LinkedList應該也是開發中比較常用的數據結構了,其基于鏈表數據結構實現,添加和刪除效率相對比較高,而隨機訪問效率偏低

特點

1.LinkedList是雙向不循環鏈表
通過查看鏈節點類:

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;}}

可以看到其有數據,上一個節點和下一個節點,所以其是雙向的

而通過查看add源碼(add->linkLast)

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;elsel.next = newNode;size++;modCount++;}

我們可以看到next的節點為null,所以LinkedList是雙向不循環鏈表

2.添加和刪除的效率相對比較高
直接添加的函數在上面已經看到了,其直接修改幾個節點地址即可做到添加操作
隨機添加的函數如下

public void add(int index, E element) {checkPositionIndex(index);if (index == size)linkLast(element);elselinkBefore(element, node(index));//node()為根據索引查找的函數,稍后再看}void linkBefore(E e, Node<E> succ) {// assert succ != null;final Node<E> pred = succ.prev;final Node<E> newNode = new Node<>(pred, e, succ);succ.prev = newNode;if (pred == null)first = newNode;elsepred.next = newNode;size++;modCount++;}

可以看到,隨機添加只是查找到對應索引的節點對象,然后通過修改地址指向來添加到指定位置的
刪除的代碼:

removeLast->unlinkLastprivate E unlinkLast(Node<E> l) {// assert l == last && l != null;final E element = l.item;final Node<E> prev = l.prev;l.item = null;l.prev = null; // help GClast = prev;if (prev == null)first = null;elseprev.next = null;size--;modCount++;return element;}

隨機刪除的代碼:(也只是修改地址指向而已)

E unlink(Node<E> x) {// assert x != null;final E element = x.item;final Node<E> next = x.next;final Node<E> prev = x.prev;if (prev == null) {first = next;} else {prev.next = next;x.prev = null;}if (next == null) {last = prev;} else {next.prev = prev;x.next = null;}x.item = null;size--;modCount++;return element;}

3.隨機訪問效率較低

public E get(int index) {checkElementIndex(index);return node(index).item;}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;}}

通過代碼可以發現,每次通過索引來獲取數據都需要遍歷,如果當前索引靠前就從first向后遍歷,否則從last向前遍歷,最壞的情況時間復雜度是n/2,所以如果用在RecyclerView.Adapter中就會出現查找的效率問題(頻繁遍歷)

4.存儲數據占用的內存空間更多

private static class Node<E> {E item;Node<E> next;Node<E> prev;}

可以看到,每次保存數據都需要將數據包在Node(節點對象)中在保存起來,然后還會有兩個對象地址,這樣每保存一條數據都會多占用一個Node對象的內存和兩個對象地址的內存

5.forEach遍歷效率比fori效率更高
使用forEach的話是每次都獲取next的節點,而使用fori就是每次都相當于隨機獲取,顯而易見的forEach效率更高

下一篇:數據結構特性解析 (五)hash表

總結

以上是生活随笔為你收集整理的数据结构特性解析 (四)LinkedList的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。