Topic describes

Given the head node of a single linked list, reverse the list and return the reversed list.

Example 1:

Input: head = [1,2,3,4,5] output: [5,4,3,2,1]

Input: head = [1,2] output: [2,1] example 3:

Input: head = [] Output: []

Tip:

The number of nodes in the linked list ranges from [0, 5000] -5000 <= node. val <= 5000

Advanced: Lists can be reversed iteratively or recursively. Can you solve the problem in two ways?

Source: LeetCode link: leetcode-cn.com/problems/re… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.

Their thinking

Suppose the linked list is 1 and 1→2→3→∅, we want to change it to ∅←1←2←3. When traversing the list, change the next pointer of the current node to point to the previous node. Because a node does not reference its previous node, it must store its previous node first. The latter node also needs to be stored before the reference can be changed. Finally, the new header reference is returned.

Code one

* 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 null; let pre = null,cur = head; While (cur){let next = cur.next; // Store the value of the current pointer to the next node cur.next = pre; // Set the current pointer to the previous digit (i.e. the current pointer is reversed). Cur = next; } return pre; };Copy the code

Code number two

* 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 null; let pre = null,cur = head; While (cur){//[cur.next,pre,cur]=[pre,cur,cur.next]; } return pre; };Copy the code