Search code examples
javaalgorithmpointersnodes

how pointer works in singly linked list?


i have this code for singly linked list and it works. I understand theoretically the principle of singly linked list, but when it comes to code I dont understand how the pointer works. my problem is in this two lines code which is part of the code mentioned in the last

p.next = new Node<>(a[i], null);
p = p.next;

why we call next by p and create new node then assign null to next at the same time through parameter.? then giving p value of p.next which supposed to be null? i tried to print out p.next and next to see if they are the same or there is difference and I got in console an address for p.next and null for next. how they differ from each other ? I need some explanation in this part of code and how the node and the pointer is created.

public class EnkeltLenketListe<T> implements Liste<T> {
private static final class Node<T>
{
    private T value;
    private Node<T> next;

    private Node(T value, Node<T> next)
    {
        this.next = next;
        this.value = value;
    }
}

private Node<T> head, tail;
private int counter;

public EnkeltLenketListe(T[] a)
{
    this();

    int i = 0; for (; i < a.length && a[i] == null; i++);

    if (i < a.length)
    {
        head = new Node<>(a[i], null);
        Node<T> p = head;
        counter = 1;

        for (i++; i < a.length; i++)
        {
            if (a[i] != null)
            {
                p.next = new Node<>(a[i], null);
                p = p.next;
                counter++;
            }
        }
        tail = p;
    }
}

Solution

  • There are two pointers here to think about. Pointer p pounts to the current node, which is the last node in the list. p.next points to what will be the next node if there will be a new node added.

    p.next = new Node<>(a[i], null);
    

    This line creates a new node in the next spot (you are adding a node to the end of the list).

    p = p.next;
    

    This line tells the current pointer p to point to the newly created node at the end of the list (it is not null, you just created a new node there).