Prompt:

Given the beginning of a singly linked list head, reverse the list, and return the new beginning of the list.

Example 1:

Input: head = [0,1,2,3]
 
Output: [3,2,1,0]

Example 2:

Input: head = []
 
Output: []

Constraints:

  • 0 <= The length of the list <= 1000.
  • -1000 <= Node.val <= 1000

Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
 
class Solution {
public:
    ListNode* reverseList(ListNode* head) 
    {
        if(!head || !head->next) return head;
 
        //previous is behind the current pointer
        //current is the one you are one
        //next is the one connection to the rest of the list
 
        //the two values that get swapped
        ListNode* current = head;
        ListNode* previous = nullptr;
 
        while(current != nullptr)
        {
            //save next node
            ListNode* next = current->next;
 
            current->next = previous;
            previous = current;
            current = next;
        }
        return previous;
    }
};
 

Explanation

So basically here is sort of how I understand it to work. For the starting point you have the current pointer, which is the head of the list, as well as the previous pointer, which while the current is the head is null. You then also need the third pointer which points to the next element in the list, this way you do not break connection with the list when you mess with the current pointer

So what you do is you save the connect with the rest of the list, by saving the next node in the list. Then what you do is you basically make the current pointer point to the previous pointer right, and then you update the previous pointer to be the current pointer. Then you update the current pointer to be the next pointer.

So you basically make the current pointer point at the previous one, then shift over by one and do it all over again. A little bit confusing but still.