The title
Given the head node of a single linked list, reverse the list and return the reversed list.
Input: head = [1,2,3,4,5] output: [5,4,3,2,1]Copy the code
Answer key
Define a pre to point to null as the head node of the reverse conversion point. Cur points to the unreversed head node. Next points to the next node of the unreversed header.
Cur next points to pre, cur. Next = pre
So when I point to it, the pre moves forward how do I move it is pre = cur;
Cur = next;
Reset next = next && next. Next
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} head * @return {ListNode} */ var reverseList = function(head) { if(! head){ return head; } let pre = null; let cur = head; let next = head.next while(cur){ cur.next = pre; pre = cur; cur = next next = next && next.next } return pre };Copy the code
\