[JavaScript] Reverse linked list

Reverse Linked List
Define a function, input the head node of a linked list, reverse the linked list and output the head node of the reversed linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Restrictions:
0 <= number of nodes <= 5000

This question uses a recursive function to recurse to the last node of the linked list. This node is the head node after the reversal, which is recorded as current.
Thereafter, each time the function returns, let the next node of the current node The next pointer of the point points to the current node.
At the same time, let the next pointer of the current node point to NULLNULL, so as to realize the partial reversal from the end of the linked list.
When the recursive functions are all out of the stack, the linked list is reversed.
An illustration of a great god in the additional discussion area:
Picture from Likou user: Xiaowu Xiaowu has no troubles
code:

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    
    
    if(head == null || head.next == null){
    
    
        return head
    }
else{
    
     
    var current = reverseList(head.next);
    //例如,1,2,3,4,5,null
    //current是5
    //head是4
    //head.next 是 5
    //head.next.next 就是5指向的指针,指向当前的head(4)
    //5-4-3-2-1-null
    head.next.next = head;
    //注意把head.next设置为null,切断4链接5的指针
    head.next = null
    }
    //每层递归返回当前的节点,也就是最后一个节点。(因为head.next.next改变了,所以下一层current变4,head变3)
    return current;
};

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/104947646