Reputation: 127
Why each time we create new node p.next
so we need to assign null to this.next
? isn't always null any way? and which role does it play in LinkedList
?
if we try to print out this.next
it will be null before we assign it to null.
System.out.println(this.next);
Result is null
Also if p.next
point to the new node
why we need to set p = p.next
to point to the same node? if the purpose to set tail to p at last, can't we just set tail = p.next
which is the last one after for loop is finished.
public class EnkeltLenketListe<T>{
private T value;
private Node<T> next;
private Node(T value, Node<T> next)
{
System.out.println(this.next);
this.next = next;
this.value = value;
}
}
private Node<T> head, tail;
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;
for (i++; i < a.length; i++)
{
if (a[i] != null)
{
p.next = new Node<>(a[i], null);
p = p.next;
}
}
tail = p;
}
}
Upvotes: 3
Views: 92
Reputation: 2436
Why each time we create new node p.next so we need to assign null to this.next?
while adding and removing a nodes, we have to make sure that nodes don't point to unintended nodes. they might have pointing to some nodes.
why we need to set p = p.next to point to the same node
to locate and maintain your position in the list while you are traversing the list, you start from head, and continue to remaining nodes. if p=p.next
, how are going to traverse the list?
can't we just set tail = p.next which is the last one after for loop is finished.
No, we can not because in this case p.next
is equivalent to p.p.next
because p
was set to p.next
inside the loop. test it by adding the following before tail=p
, you should get null
System.out.println(p.next);
Edited:
your list is singly linked list which means every node except the tail should have a pointer to next node, you started with
head = new Node<>(a[i], null);
Node<T> p = head;
in this case p
and head
are pointing Node 0
see image below. if the next NOde in the array is not null, let see what happens in the for loop
p.next = new Node<>(a[i], null);
p = p.next;
In this case p.next
is pointing to Node 1
(see image below), where as p
which were pointing to Node 0
is now set to point to Node 1
. so both are pointing to 'Node 1`. the last one:
tail = p;
You said that why don't we just tail=p.next
? No, we can not because in this case p.next
is equivalent to p.p.next
because p
was set to p.next
inside the loop.
read about singly linked list here
Upvotes: 3
Reputation: 18838
Try to use contradiction. If you didn't set p = p.next
, in the next iteration of the loop, again you will set the new node to the next position of the previous node. Hence, all the time p
is the head
and you didn't move the p
anymore!
Therefore, you need to move p
in each iteration after setting p.next
. Indeed, it is a pointer to the last element of the list.
Upvotes: 3