简体   繁体   English

LinkedList中的新元素在哪里添加? 在头还是尾?

[英]Where does the new element in the the LinkedList gets added? in after the head or at the tail?

I had read in some blog that the new node gets added the the front. 我在一些博客中读到,新节点被添加到最前面。 But when i checked the source code of the linkedList , it adds the node at the last and keeps the head address of the list constant, which should be the ideal behavior. 但是,当我检查linkedList的源代码时,它在最后添加了node ,并保持列表的head地址恒定,这应该是理想的行为。

public boolean add(E e) {
        linkLast(e);
        return true;
}
 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;
        else
            l.next = newNode;
        size++;
        modCount++;
 }

Is there any difference in the Node addition behavior of the singly and doubly linked Lists? 单链表和双链表的节点添加行为是否有所不同?

From the documentation : 文档中

add(E e) 加(E e)

Appends the specified element to the end of this list . 将指定的元素追加到此列表的末尾

(my emphasis) (我的重点)

As far as I know, where is no single linked list in java library. 据我所知,java库中没有哪个链表。 You can create your own. 您可以创建自己的。 And I think the only difference will be in: save or not save back link. 我认为唯一的区别是:保存或不保存返回链接。

the LinkedList implementation of Java is a double linked list. Java的LinkedList实现是一个双链表。 So you can use all of its features. 因此,您可以使用其所有功能。 If you look at the Methods you can use, there is a addLast and addFirst which does exactly the name says. 如果您看一下可以使用的方法,则有一个addLast和addFirst,它们的名称完全相同。 And the doc of the add method of the List interface says it falls back to addLast. List接口的add方法的文档说,它回落到addLast。 This should answer your question. 这应该可以回答您的问题。

In common in a single linked list addLast is O(n) and in a double linked list it is O(1) since you have a reference to the tail as well. 在单链表中,addLast通常为O(n),在双链表中,它通常为O(1),因为您也引用了尾部。 AddFirst is all the time O(1). AddFirst始终为O(1)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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