简体   繁体   English

试图了解有关Java中的节点和链表的更多信息

[英]Trying to understand more about the nodes and linkedlist in java

I just began to learn LinkedLists and nodes and I don't understand something in this code :¸ 我刚刚开始学习LinkedLists和节点,但是我对这段代码不了解:¸

public class ListeChainee<E> {

private Noeud debut=null;
private Noeud fin=null;
private int taille=0;

private class Noeud 
{
    private E contenu;
    private Noeud suivant;

    Noeud(E contenu, Noeud suivant)
    {
        this.contenu=contenu;
        this.suivant=suivant;
    }
}
public boolean add(E element)
{
    Noeud n= new Noeud(element,null);

    if(taille==0)
        debut= n;           
    else
        fin.suivant=n;      
    fin=n;
    taille++;
    return true;
}

And in my main class, i have this : 在我的主班上,我有这个:

ListeChainee<Integer> liste= new ListeChainee<Integer>(); liste.add(2); liste.add(3);

I'm trying to understand why when I do "liste.add(3)", debut.suivant changes ? 我试图了解为什么当我执行“ liste.add(3)”时,debuty.suivant会发生变化? Thank you for your help 谢谢您的帮助

When you add 2, it is the first node in the list, thus debut point to it. 当您添加2时,它是列表中的第一个节点,因此是它的首次亮点。 but it has no successors, thus suivant is null. 但它没有后继者,因此suivant为null。

When you add 3, 2 needs to point to 3, so 2's suivant link points to 3. it just so happens that since 2 is the first node, you see this change in debut.suivant, as debut and fin are the same node at this point. 当您添加3时,2需要指向3,因此2的suivant链接指向3。这恰好是因为2是第一个节点,所以您看到了launch.suivant的这一变化,因为Premiere和fin是同一节点。这点。

debut.suivant changes when you execute "liste.add(3)" because debut and fin reference the same Noeud when the list contains a single Noeud, therefore inside the add method fin.suivant = n is the equivalent to debut.suivant = n when the second node is added. 当您执行“ liste.add(3)”时,debuty.suivant会发生变化,因为当列表包含单个Noeud时,debuty和fin引用相同的Noeud,因此在add方法中fin.suivant = n等同于premiere.suivant = n添加第二个节点时。

Consider the following lines of code to understand why debut == fin for the first Noede of the list: 考虑以下代码行,以了解为什么对列表的第一个Noede首次亮相== fin:

if(taille==0)
    debut= n;           
...  
fin=n;

Both debut and fin are assigned n, therefore when fin.suivant is changed in the second add, so is debut.suivant. 首次亮相和fin都被分配为n,因此,在第二个加法中更改fin.suivant时,也将首次亮相。

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

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