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;
}
};
Top comments (0)