“This is the 17th day of my participation in the August More Text Challenge.

The problem defines a function that takes the head node of a linked list, reverses the list, and outputs the head node of the reversed list.

Train of thought

We define a cur pointer to the head node and a pre pointer initialized to null.

To do the reverse, save the cur->next node as TMP.

Why do I save this node? Because then I’m going to change the direction of cur-> Next, and I’m going to change the direction of cur-> Next to pre, which has reversed the first node.

The next step is to loop through the following code logic and continue moving the pre and cur Pointers.

Finally, the cur pointer points to NULL, the loop ends, and the list is reversed. So we just return the pre pointer, and the pre pointer points to the new header.

var reverseList = function(head) {
    var prev = null;
    var curr = head;
    while(curr ! = =null) {
        let cnext = curr.next; 
        curr.next = prev 
        prev = curr
        curr = cnext

    }   
    return prev
};

Copy the code