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

mayankdv

Mayank Arora

Posted on August 5, 2022

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.

💖 💪 🙅 🚩
mayankdv
Mayank Arora

Posted on August 5, 2022

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

Sign up to receive the latest update from our blog.

Related