LeetCode-flip linked list (JS implementation)

Title description

Problem-solving ideas

  • First use a node pointer to record the head pointer
  • Use a while loop to traverse the linked list and save each value in the linked list in an array.
  • Then use the result pointer to record the head pointer, and the node pointer starts to traverse backward
  • Each time the node pointer is traversed, the data field is modified to an array.pop
  • Finally return the result pointer

Implementation code

var reverseList = function(head) {
    
    
    // 首先遍历这个链表
    let arr = [];
    let node = head;
    while(head) {
    
    
        arr.push(head.val);
        head = head.next;
    }
    let result = node;
    while(node) {
    
    
        node.val = arr.pop();
        node = node.next;
    }
    return result;
};

Guess you like

Origin blog.csdn.net/sinat_41696687/article/details/115061744