Java – what role does each node play in the linked list?
Why do we need to create a new node p.next for this every time Next allocation null? Isn't it always empty? What is its role in LinkedList?
System.out.println(this.next);
The result is empty
In addition, if p.next points to a new node, why do we need to set P = p.next to point to the same node? If we finally set tail to the purpose of P, we can't just set tail = p.next, which is the last one after the end of the for loop
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; } }
Solution
When adding and deleting nodes, we must ensure that nodes do not point to unexpected nodes They may point to certain nodes
When traversing the list, find and maintain the position in the list, start from scratch and continue to keep the nodes If P = p.next, how do I traverse the list?
No, we can't, because in this case, p.next is equivalent to p.p.next, because P is set to p.next in the loop Test it by adding the following before tail = P, and you should get null
System.out.println(p.next);
Edit:
Your list is a single linked list, which means that every node except the tail should have a pointer to the next node. You can start using it
head = new Node<>(a[i],null); Node<T> p = head;
In this case, P and head point to node 0, as shown in the figure below If the next node in the array is not null, let's see what happens in the for loop
p.next = new Node<>(a[i],null); p = p.next;
In this case, p.next points to node 1 (see the figure below), where p pointing to node 0 is now set to point to node 1 So both point to node 1 the last one:
tail = p;
Why do you say we're not just tail = p.next? No, because P is set to p.next. Within the loop
read about singly linked list here