DEV Community

Mayank Arora
Mayank Arora

Posted on

206. Reverse Linked List[Leetcode][C++]

All suggestions are welcome. Please upvote if you like it. Thank you.


Leetcode Problem Link: 206. Reverse Linked List


Using Recursion:

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

Enter fullscreen mode Exit fullscreen mode

Using Iteration:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *prev=NULL, *curr=head, *next=NULL;
        while(curr){
            next=curr->next;
            curr->next=prev;
            prev=curr;
            curr=next;
        }
        head=prev;
        return head;
    }
};

Enter fullscreen mode Exit fullscreen mode

All suggestions are welcome. Please upvote if you like it. Thank you.

Top comments (2)

Collapse
 
george_witha_j profile image
George Withaj

Awesome!

Collapse
 
mayankdv profile image
Mayank Arora

Thank you George for the compliment.