js: array to linked list, linked list to array

linked list node

head, the head node

function ListNode(val, next) {
    
    
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}

1. Array to linked list

Create linked list nodes according to the values ​​in the array, and hang them into the linked list one by one

export function array2List(arr) {
    
    
    if(arr.length === 0) {
    
    
        return null
    }
    
    const head = new ListNode(arr[0])
    let p = head
    for(let i=1; i<arr.length; i++) {
    
    
        p = p.next = new ListNode(arr[i])
    }
    return head
}

2. Linked list to array

Traverse the linked list, store the value of the linked list node in the array

export function list2Array(head) {
    
    
    const arr = []
    while(head) {
    
    
        arr.push(head.val)
        head = head.next
    }
    return arr
}

Guess you like

Origin blog.csdn.net/qq_38432089/article/details/126760240