Reputation: 197
I am facing a conceptual issue with references in java. This is my implementation of a basic LinkedList
:
The Nodes:
class Node {
int data;
Node next = null;
public Node(int data) {
this.data = data;
}
}
The List:
class LinkedList {
Node n = null;
Node start = null;
int flag = 0;
void insertion(int x) {
if(flag==0)
{
Node newnode = new Node(x);
n = newnode;
start = newnode;
flag = 1;
return;
}
Node newnode = new Node(x);
n.next = newnode;
n = n.next;
}
void deletion() {
Node str = start;
while(str.next.next != null)
str = str.next;
str.next = null;
}
void printlist() {
Node str = start;
while(str != null) {
System.out.println(str.data);
str = str.next;
}
}
}
Test Class:
public class Test31 {
public static void main(String[] args){
LinkedList ll = new LinkedList();
ll.insertion(5);
ll.insertion(15);
ll.insertion(25);
ll.insertion(35);
ll.insertion(45);
ll.insertion(55);
ll.deletion();ll.deletion();
ll.printlist();
}
}
The above program works perfectly fine without any problem, but if I replace deletion()
with this piece of code:
void deletion() {
Node str = start;
while(str.next != null)
str = str.next;
str = null;
}
Then deletion of elements does not take place. I am interested in knowing that why this is happening. Using str.next.next
does the trick, but if I use the deletion method given above shouldn't it also achieve the same effect with just one more iteration of while loop?
Upvotes: 1
Views: 89
Reputation: 10473
This is because one of the str.next
objects still has a reference to it (or potentially start
is referencing it). By setting str
to null, you are simply setting the local variable in that method to null
, but by setting str.next
to null, you are deleting the reference in that str
object.
Simple example:
Node start = new Node();
Node another = new Node();
start.next = another;
Node toDelete = another;
If you do this:
toDelete = null;
In this case, toDelete
is now null
. start.next
and another
still contain references to the object another
was originally assigned to. Even if you append this:
another = null;
In this case, there's still one reference left. start.next
still points to the original object that another
was initially assigned to.
I think the first deletion method is actually incorrect too, as it will never delete the starting node and will throw a NullPointerException
if you only have one node in it since start.next
is null
and the while loop is attempting to get to start.next.next
. I think this is more accurate:
void deletion() {
Node parent = null;
Node current = start;
while (current.next != null) {
parent = current;
current = current.next;
}
if (parent == null) {
start = null;
flag = 0;
} else {
parent.next = null;
n = parent;
}
}
Upvotes: 3