Skip to content

Reverse a Linked List Recursively

Leetcode-206 Reverse Linked List Difficulty: Easy

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:

Input: head = [1,2]
Output: [2,1]

Example 3:

Input: head = []
Output: []

Constraints:

  • The number of nodes in the list is the range [0, 5000].
  • -5000 <= Node.val <= 5000

Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both?

Source: Leetcode

ALERT, ALERT, ALERT !!!

If you have come to see the solution before trying to solve it yourself, this really won’t help you, promise! If that is the case, we will recommend, please go back and first try it yourself. If you can’t solve it after (at least)an hour of thinking and trying, please come back! 🙂You can solve it here

__________________________________________________________

Recursive Solution

Let’s consider we have a linked list like below. A single node of list has 1) a value part and 2) a pointer that points to the next element.

A separate head pointer points to node A, next pointer of A points to B and so on. Finally, D is the last element of list, so, it points to NULL. After the list is reversed, D will be the first element and A will be the last element.

The idea of recursive solution is, we will traverse forward from A to D, then will return D and traverse backward to A. During the backward traversal, we will change each pointer’s direction so that they point to their respective previous element. For example, D will point to C, C will point to B and so on. Finally, being the last element, node A of the reversed list will point to NULL. So, let’s see how the recursive algorithm will work as we traverse forward and then backward.

Forward Traversal

The above image shows how forward traversal will look like for each step from A to D. Each recursion call creates a stack frame for the local variables. So, in step-1, A will be stored in stack, then B in step-2, then C and so on. Finally, D points to NULL, so there will be no more recursive calls. Instead, D will be returned. In the code, this is like:

if (head->next == NULL) return head; // in case of D, head = D

Backward Traversal

Returned value of D will be received by C. For that, we will use a variable named tail. From C, this will be returned to B. So, ultimately C is returning D to B. Similarly, B will return D to A, and finally A will also return D to the caller of recursive function. This way, we will receive D as the head of the reversed linked list.

Now, for each node, before returning D to it’s previous node, some magic will happen! Let’s take C for example. Before returning D to B (using tail variable), C will make D to point back to C. Formally, we need to do C->next->next = C and then C->next = NULL. In code, this is like:

head->next->next = head; head->next = NULL;

Let’s see how the backward traversal will work visually.

Backward Traverse – D to C

Backward Traverse – C to B

Backward Traverse – B to A

Final List

Code

class Solution {
public:
    ListNode* rec(ListNode* head) {
        if(head->next == NULL)
            return head;
        ListNode* tail = rec(head->next);
        head->next->next = head;
        head->next = NULL;
        return tail;
    }
    
    ListNode* reverseList(ListNode* head) {
        if(head == NULL) return head;
        return rec(head);
    }
};

Thanks for reading. Please let us know if any part of this tutorial is hard to understand. Comment if you like it, hate it or want to suggest for improvement.

Happy Coding ! 😀

49 thoughts on “Reverse a Linked List Recursively”

  1. This site is really a walk-by means of for all of the data you needed about this and didn’t know who to ask. Glimpse here, and also you’ll undoubtedly uncover it.

  2. I was wondering if you ever considered changing the page layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or 2 images. Maybe you could space it out better?

  3. Apoiar ferramentas de apostas e estar equipado com uma plataforma diversificada de transações financeiras, a 20Bet oferece suporte tangível aos jogadores. Este é um lugar onde eles podem apostar com dinheiro real, respaldados por concorrentes de diversas disciplinas esportivas. 20bet

  4. Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you. 20bet

  5. It’s really a nice and useful piece of information. I’m glad that you shared this helpful info with us. Please keep us informed like this. Thank you for sharing.

  6. Hello! Someone in my Myspace group shared this website with us so I came to take a look. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Excellent blog and terrific design and style.

  7. Dear foolishhungry.com administrator, You always provide great examples and case studies.

  8. I’ve been exploring for a little bit for any high-quality articles or weblog posts on this sort of space . Exploring in Yahoo I at last stumbled upon this site. Studying this info So i am satisfied to express that I’ve an incredibly just right uncanny feeling I came upon just what I needed. I such a lot indubitably will make certain to don’t omit this website and give it a look on a continuing basis.

  9. Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me.

  10. Great write-up, I’m normal visitor of one’s site, maintain up the nice operate, and It’s going to be a regular visitor for a lengthy time.

  11. What Is Sugar Defender? Sugar Defender is a natural blood sugar support formula created by Tom Green. It is based on scientific breakthroughs and clinical studies.

  12. naturally like your web site however you have to test the spelling on several of your posts. Several of them are rife with spelling issues and I in finding it very bothersome to inform the truth however I¦ll definitely come back again.

  13. Thanks for the sensible critique. Me and my neighbor were just preparing to do a little research about this. We got a grab a book from our area library but I think I learned more from this post. I am very glad to see such excellent information being shared freely out there.

  14. What i do not realize is actually how you are not actually much more well-liked than you might be right now. You are very intelligent. You realize thus considerably relating to this subject, produced me personally consider it from numerous varied angles. Its like men and women aren’t fascinated unless it’s one thing to do with Lady gaga! Your own stuffs outstanding. Always maintain it up!

  15. I want to express my appreciation to this writer for bailing me out of this problem. As a result of scouting through the online world and coming across principles that were not helpful, I figured my life was over. Living minus the approaches to the problems you’ve sorted out as a result of your main review is a serious case, and those that might have in a negative way affected my entire career if I had not noticed your web site. Your actual capability and kindness in dealing with almost everything was valuable. I don’t know what I would’ve done if I hadn’t encountered such a point like this. It’s possible to at this time look forward to my future. Thanks for your time very much for this reliable and effective help. I won’t hesitate to suggest the sites to any individual who wants and needs assistance about this issue.

  16. Hi foolishhungry.com admin, You always provide great examples and real-world applications.

  17. whoah this blog is fantastic i love reading your articles. Keep up the great work! You know, a lot of people are hunting around for this info, you can aid them greatly.

Leave a Reply

Your email address will not be published. Required fields are marked *