DEV Community

Cover image for Reverse Linked List | Leetcode Problem
Shashank Shekhar
Shashank Shekhar

Posted on

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

Top comments (0)