简体   繁体   中英

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 :¸

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 ? Thank you for your help

When you add 2, it is the first node in the list, thus debut point to it. but it has no successors, thus suivant is 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.

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.

Consider the following lines of code to understand why debut == fin for the first Noede of the list:

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.

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