Reverse Linked List | Leetcode Problem
Shashank Shekhar
Posted on January 12, 2022
Problem Statement
Given the head of a singly linked list, reverse the list, and return the reversed list.
Example:
**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;
}
};
💖 💪 🙅 🚩
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.