Reverse LinkedList in Java

I discuss the solution in this post Reversing a linked list in Java, recursively

I copied one of the solutions below. I implemented it and it works great.

public ListNode Reverse(ListNode list)
{
    if (list == null) return null; // first question

    if (list.next == null) return list; // second question

    // third question - in Lisp this is easy, but we don't have cons
    // so we grab the second element (which will be the last after we reverse it)

    ListNode secondElem = list.next;

    // bug fix - need to unlink list from the rest or you will get a cycle
    list.next = null;

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.Next = list;

    return reverseRest;
}

I do not understand, however, these are the last few lines.

secondElem.next = list;
return reverseRest;

It seems we are not returning the second character at all? But I debugged the code and looked like secondElem already inside reverseRest. Is it because it is a reference by value in Java and is it automatically updated upon application secondElem.Next=list?

+3
source share
3 answers

Do not think about the transfer of semantics, think in terms of objects in memory and variables that contain references to them.

The initial state:

(list)
   |
   V
[  1  ] -> [  2  ] -> ... -> [  N  ]

After list.next = null;:

(list)   (secondElem)
   |          |
   V          V
[  1  ]    [  2  ] -> ... -> [  N  ]

:

(list)   (secondElem)      (reverseRest)
   |          |                 |
   V          V                 V
[  1  ]    [  2  ] <- ... <- [  N  ]

secondElem.Next = list;:

(list)   (secondElem)      (reverseRest)
   |          |                 |
   V          V                 V
[  1  ] <- [  2  ] <- ... <- [  N  ]
+5
+4

, , .

secondElem.next = list;
return reverseRest;

2 , :

1.secondElem.next = list;

, secondElem . secondElem .

:

    // then we reverse everything from the second element on
    ListNode reverseRest = Reverse(secondElem);

    // then we join the two lists
    secondElem.Next = list;

:

ListNode reverseRest = Reverse(list.next);    
list.next.next = list;

. !

2. return reverseRest;

reverseRest . - , ( ) , . , , reverseRest - , Reverse (secondElem), " " !

0

Source: https://habr.com/ru/post/1772270/


All Articles