0

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.

wjxiz
  • 153
  • 1
  • 1
  • 12
  • 1
    You need to pass the whole list to the method and only then manipulate its fields or return a modified list. Otherwise it is not going to work. Java is pass by value. You cannot pass a `Node` as parameter and work on it. – Grzegorz Górkiewicz Jan 19 '17 at 23:21
  • Java is pass by reference. let me explain. lets say node1 is reference Ref1. You pass it the method removeNode and now head is Ref2. Ref1 and Ref2 both pointing to Obj1. Now if you do manipulation of Obj1 properties (like Ref2.item = 10). It will be reflected when u will do Ref1.item. But, if you point Ref2 to a new location then the reference is being pointed to a new Object Obj2. and Ref1 is still pointing to Obj1. I Hope it helps !!! – Deepak Agarwal Jan 19 '17 at 23:50

0 Answers0