简体   繁体   中英

Are there any performance differences between singly- and doubly-linked lists?

Our homework assignment asks us to prove that the Java LinkedList implementation is doubly-linked and not singly-linked. However, list operations such as adding elements, removing elements, and looking elements up seem to have the same complexity for both implementations, so there doesn't seem to be a way to use a performance argument to demonstrate the doubly-linked nature of Java's LinkedList . Anyone know of a better way to illustrate the difference between the two?

看一下在向前或向后方向上进行迭代,删除“ before-last”元素,等等。

这很容易证明-您查看源代码,看每个节点都有一个.previous指针:) http://www.docjar.com/html/api/java/util/LinkedList.java.html

Consider the following nodes, single and double.

class SingleLinkedNode { E data; SingleLinkedNode next; }

class DoubleLinkedNode { E data; DoubleLinkedNode prev; DoubleLinkedNode next; }

If we want to remove from a DoubleLinkedList (assuming we have already FOUND the node, which is very different) what do we need to do?

  1. Make the node before the deleted one point to the one after.
  2. Make the node after the deleted one point to the one before.

If we want to remove from a SingleLinkedList (assuming we have already FOUND the node, which is very different) what do we need to do?

  1. Make the node before the deleted one point to the one after.

You'd think that means it's even faster in a single linked list than a double.

But, how are we doing to delete the node if we don't have a reference to the one before it? We only have a reference to the next. Wouldn't we have to do a whole other search on the list just to find prev? :-O

The Java List interface doesn't have a method which allows you to remove an item without searching through a linked list. It has remove(int index), which would have to scan the list to find the indexed entry, and it also has remove(Object o), which has to scan the list as well. Since a linked list implementation can save the necessary previous-item entry context while scanning, remove has equivalent complexity for singly- and doubly-linked lists. This state can be saved in an iterator, as well, so Iterator.remove() doesn't change this. So I don't think you can tell from remove performance.

My guess is that the "right" answer to this is to create several lists of different sizes and time the performance of .indexOf() and .lastIndexOf() when searching for the first or last object. Presuming that the implementation is doubly-linked and searches from the beginning of the list for .indexOf() and searches from the end for .lastIndexOf(), the performance will be length-dependent or length-independent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM