C++ Solution, in-place, 3 pointers


  • 0
    A

    This is my solution for reverse linked list. It includes in-place swapping of pointers of node in linked list using 3 pointers, back, cur and ahead, which point to consecutive nodes in that order. We change the next pointer of cur node to back . ahead points to the next node whose pointer is to be reversed.

    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            if(head == NULL) return head;
            ListNode* back = head;
            ListNode* cur = head->next;
            ListNode* ahead = NULL;
    
            while(cur){
                ahead = cur->next;
                cur->next = back;
                back = cur;
                cur  = ahead;
            }        
            head->next = NULL;
            return back;
        }
    };
    

Log in to reply
 

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