Why null value cannot be passed in reference?


  • 0
    K

    I'd like to ask why the null value cannot be passed back via reference. In this code, as the line marked, if I change curr's value, the linkedlist gonna change, however, if I set curr to equal to null, the linkedlist is not affected.

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode removeElements(ListNode head, int val) {
      // corner cases
      if(head==null) return null;
      ListNode curr = head;

       while(curr!=null){
           if(curr.val == val){
               if(curr.next!=null){
                   curr.val = curr.next.val;
                   curr.next = curr.next.next;
               }else{
                   curr=null; //this line gives the error, that though curr equals to null afterwards, it won't affect the list
               }
           }else{
               curr = curr.next;
           }
       }
       
       return head;
      

      }
      }


  • 0
    J

    Set the current pointer to null does not help in this case. It just remove one reference from the node which you intend to remove. However, the pointer to this target node is still there via the next reference of the previous node. So the correct implementation is to set the next node of the previous node (in the list) to null.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.