Easy C++ iterative solution with comments


  • 0
    N
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode *prev, *curr, *n_next;
            
            //If there are no nodes or single node
            if(!head || !head->next) return head;
            
            prev = nullptr;
            curr = head;
            n_next = head->next;
            
            //Iterate till the current points to last node
            while(n_next) {
                curr->next = prev;
                prev = curr;
                curr = n_next;
                n_next = n_next->next;
            }
            
            //connect the last node to the list
            curr->next = prev;
            head = curr;
            return head;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.