Reverse Linked List | Leetcode Problem

ssshekhu53

Shashank Shekhar

Posted on January 12, 2022

Reverse Linked List | Leetcode Problem

Problem Statement

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

Example:

Image description

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

Link to the question: https://leetcode.com/problems/reverse-linked-list/

Solution

class Solution {
public:
    ListNode* reverseList(ListNode *cur, ListNode *next) {
        ListNode *last;
        if(next->next!=nullptr)
            last=reverseList(next, next->next);
        else
            last=next;
        next->next=cur;
        return last;
    }

    ListNode* reverseList(ListNode* head) {
        ListNode *last;
        if(head==nullptr || head->next==nullptr)
            return head;
        if(head->next!=nullptr)
            last=reverseList(head, head->next);
        head->next=nullptr;
        return last;
    }
};
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
ssshekhu53
Shashank Shekhar

Posted on January 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related