Agustín Samper
Agustín Samper

Reputation: 31

Add an element at the end of a LinkedList<T>

I have a code which add a node at the end of a LinkedList but I don't understand how it works: when the code ends else statement the top node has the previous elements and add the pointer elements at the final of the list.

I don't know when the pointer elements are added at top node. Why does this happen and how does it works?

//Link element as latest of the List
public void addAtTheEnd(T element) {
    Node<T> aux = new Node<>(element);
    
    if(this.isEmpty()) {
        top = aux;
    } else {
        Node<T> pointer = top;            
        while (pointer.getNext() != null) {
            pointer = pointer.getNext();
        }
        pointer.setNext(aux);
    }
    size++;
}

enter image description here

enter image description here

Upvotes: 2

Views: 160

Answers (3)

user3200120
user3200120

Reputation:

Great answers but I found this explanation slightly clearer:

  1. You create an "aux" Node and pass the argument "element" to the Node constructor.
  2. If your list is empty, there's no other nodes, so you simply set "top" as the node "aux" (the Node you've just created).
  3. Else, you create a pointer pointing to the "top" node and loop until it doesn't have a reference to the next element. When you reach that point (aka the last element, where you have no next), you set it's next node to "aux", making aux the last node.

Upvotes: 0

Abhishek
Abhishek

Reputation: 21

  1. Assume your node is Empty i.e. the code goes in the IF block and the aux node gets attached to the top node.
  2. Now if the node is not empty then it goes in the else block where it makes a new Pointer initialized with the top node. The while loop iterates till it finds a pointer which has null value. And finally attaches the new aux node at the end pf the node. To get proper visual idea you may watch youtube channels like mycodeschool.

Upvotes: 1

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11136

It's simple:

  1. if block (your list is empty): Node just gets added as the first and only element, hence it's the top and it's the last;

  2. else block (your list is not empty): You iterate over the nodes, namely you move to the next node, again, and again, until you reach the last (tail) one, and the moment you reach it - you add the received argument(node) as the next node of the currently last one.

I hope this helps.

Upvotes: 2

Related Questions