Reputation: 31
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++;
}
Upvotes: 2
Views: 160
Reputation:
Great answers but I found this explanation slightly clearer:
Upvotes: 0
Reputation: 21
Upvotes: 1
Reputation: 11136
It's simple:
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;
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