Error in Code, Need Help


  • 0
    J

    This code has a problem and I think I know what it is:
    When I set "node = null;" node is being passed by value instead of reference.
    I thought all objects in Java were passed by reference and all primitive data was passed by value.

    So why is ListNode being passed by value? (It's an object)

    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode node = head;
            int size = 0;
            
            while(node != null) {
                node = node.next;
                size++;
            }
            
            node = head;
            
            for(int i = 0; i < size - n; i++) {
                node = node.next;
            }
            
            if(node.next == null)
                node = null;
    
            else if(node.next.next == null)
                node.next = node.next.next;
    
            return head;
        }
    }

Log in to reply
 

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