Java Solution with detailed explaination

  • 1

    lets take 1->2->3->4 as an example, hope this can help you to get basic understanding of how to use recursive method.

    public class Solution {
    public ListNode reverseList(ListNode head) {
    if(head ==null|| == null) return head; //here is the base case

    ListNode second =; //here "second" means "2->3->4", aka. the rest part

    ListNode rest = reverseList(second); //here, we use recursive method to take care of the rest part, if you think it's hard to understand, just ignore all those steps and tell yourself, recursive will take care of this and help me to change "2->3->4" to "4->3->2", so here , "rest" is the head "4" of this linked list that we just got, now all we need to do is to make sure is 1, and 1->next = null; = head; // here we make sure = 1, recall that the pointer "second" is still point to "2", and pointer 'head' points to '1';so we get '4->3->2<=>1' since still points to second(2), lets get rid of this now = null; // here we get rid of the "1->2", now what left is "4->3->2->1" which is what we need;

    return rest; // as i said, 'rest' points to '4' aka the head of '4->3->2->1', here we return rest aka the result linked list

Log in to reply

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