简体   繁体   中英

Update value of a reference in recursive method - best practices

I am trying to see how I can update a reference variable in Java methods in a better way. I know that Java references are pass by value - in other words, if I change the value of the reference in a method, it wont retain it in the caller method. But at the same time, I am trying to see how I can deal with these situations better. In most cases we need to return value from a method in recursion, say its base case, just like below where I resort to maintaining a static variable to hold the new head of a linked list that is being reversed. What are the more sensible options that I can use here?.

public static LinkedList _head = null;
    public static LinkedList reverseLinkedList(LinkedList head) 
    {
        reverseLinkedListInternal( head );
        return _head;
    }
    
    public static LinkedList reverseLinkedListInternal( LinkedList node )
    {
        if( node.next == null )
        {
            _head = node;
            return node;
        }

        LinkedList tmp = reverseLinkedListInternal( node.next );
        tmp.next = node;
        node.next = null;
    
        return node;
    }

You just don't need the static variable here. You should be just using the return value, whereas at the moment it's simply being ignored.

This is the kind of solution I would write. Obviously this might not fall into the constraints of your exercise as it is written as if it were a method of a LinkedList , which would make a lot more sense in the real world. However the concept is the same, so hopefully it will help you to spot your mistakes.

public void reverse() {

    reverseInternal(head);
}

public Node reverseInternal(Node node) {

    if (node.next == null) {

        return node;
    }

    Node reversedTail = reverseInternal(node.next);
    reversedTail.next = node;
    node.next = null;

    return reversedTail;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM