Reverse Linked list solution with comments

//TIME COMPLEXITY O(n)
 //SPACE COMPLEXITY O(1)

ListNode* Solution::reverseList(ListNode* head) {

    //intially new head is pointing to NULL
    ListNode*  newHead=NULL;
    ListNode*  nextOfHead; // nextOfHead to point to next of head so that we can keep track  rest of linklist
    
    while(head!=NULL){  // the moment head reaches to NULL we gonna return newHead as it will be pointing to lastnode of linklist
        nextOfHead=head->next;   // nextOfhead is pointing to next of head
        head->next= newHead;  //reverse the link

        newHead=head;         // assign newHead to head
        head=nextOfHead;      // assign head to nextOfHead
    }
  
   return newHead;
}

Click here to start solving coding interview questions