Weird result passing by reference?

  • 0

    I created a helper function called reverse(ListNode)

    void reverse(ListNode node){
        	if(node != null && != null){
                ListNode ptr =;
       = null; // set it to end
                while(ptr != null){
                    ListNode tmp =;
           = node;
                    node = ptr;
                    ptr = tmp;
            System.out.println("reversed: " + node.toString());

    So inside the function, I get the correct result, but when the function return the node by reference, it goes wrong, can anyone help me figure out this ?

  • 0

    I figure this out, java is passing by value, not by reference, so one can't do that with a wrapper function, what to do is to simply just reverse the list inside the reorderList function

  • 0

    I am only familiar with C++.
    Why your code is passing by ref?
    Could you try to return this result, and check the result?
    For C++, you can pass a pointer to the function, by this pointer is passed by value. If you change the value pointed by this pointer, everything is ok. But if you change the value of the pointer, the result will not be returned.

  • 0

    Actually it is passed by reference(and not by value) in Java and the behavior you are getting is normal.You can solve it by making your helper method return the new head

Log in to reply

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