Why head=head.next doesn't work


  • 2
    H

    Question in the code, any know why? Thanks a lot!

    public TreeNode sortedListToBST(ListNode head) {
        if(head==null) return null;
       ListNode countlen=head;
       int len=0;
       while(countlen!=null){ countlen=countlen.next;len++;}
    
      return sortedList(head,0,len-1);  // first find the length of linkedlist
        
    }
    public TreeNode sortedList(ListNode head, int start, int end){
        if(start>end) return null;
        int mid=start+(end-start)/2;
        TreeNode left=sortedList(head,start, mid-1);    //go through the listedlist from left to right to build the tree
        TreeNode root= new TreeNode(head.val);
         root.left=left;
        if(head.next != null){
            // head.val = head.next.val;
            // head.next = head.next.next;
            head=head.next;    //i don't know why why this doesn't work, only I wrote in the above format it can accept, is there any different?
        }
         root.right=sortedList(head, mid+1, end);
        return root;
    }

  • 0
    P
    public TreeNode sortedList(ListNode head, int start, int end)
    

    head should be a pointer


  • 0
    M

    I'm pretty sure this is Java, so there are no explicit pointers.


  • 3
    M

    Looking at the code you've presented, the

    if(head.next != null){
        // head.val = head.next.val;
        // head.next = head.next.next;
        head=head.next;
    }
    

    does have a rather significant difference between the two. In the head=head.next;, the local variable advances to the next node in the list, while head outside of the method remains the same. On the other hand,

    // head.val = head.next.val;
    // head.next = head.next.next;
    

    does have a severe side effect when run. Inside the method, there is no change in outcome, but you are changing the node itself, so the advance is occurring outside the method as well. Basically, the current one advances in the method, but not outside, while the second advances both inside and outside the method.


  • 0
    S

    As mike3 said, in your block:

    if(head.next != null){
      // head.val = head.next.val;
      // head.next = head.next.next;
      head=head.next;
    }
    

    you are not doing anything but advancing one place or, in the case of the commented-out code, just changing the values of the current node. What you need to do is instead is to advance places – preferably using another variable – until you reach mid, and then pass that one ListNode's next to build the right side of the tree.

    Similarly your root shouldn't be the head but the middle node at mid.


Log in to reply
 

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