I met a problem when I want to remove a specific Node from a NodeList,
void removeNode(Node head, int value){
if (head == null) {
System.out.println("error : Null linkedList");
} else {
Node cur = null;
if (head.item == value) {
//The problem is here.
head = head.next;
} else {
cur = head;
while( cur.next != null && cur.next.item != value) {
cur = cur.next;
}
if(cur.next != null && cur.next.item == value){
cur.next = cur.next.next;
}
}
}
}
as you know that the form of a Node is defined:
public class Node{
int item;
Node next;
}
and my test goes like this:
void test(){
Node node1 = new Node();
Node node2 = new Node();
Node node3 = new Node();
Node node4 = new Node();
node1.item = 1;
node2.item = 2;
node3.item = 3;
node4.item = 4;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = null;
}
It went well when I do
removeNode(node1,2);
removeNode(node1,3);
removeNode(node1.4);
but I can't remove the first node
removeNode(node1,1);
It doesn't work, So I set a debug point at this sentence. In debug mode, I saw clearly that after executing this sentence, "node1 " turns to be "node2" whose "item" equals to "2". But after exiting the whole "removeNode", node1 returned to original "node1" whose "item" equals "1".
I thought that the "head" I use in the method is a copy of the node1, but I learned that Java always use reference passing parameters. I am confused what "head" really is inside the method.