单链表的倒数第 k 个节点

/**
 * 单链表的倒数第k个节点
 */
const linkList = {
    value: 1,
    next: {
        value: 2,
        next: {
            value: 3,
            next: {
                value: 4,
                next: {
                    value: 5,
                    next: {
                        value: 6,
                        next: {
                            value: 7,
                            next: {
                                value: 8,
                                next: {
                                    value: 9,
                                    next: {
                                        value: 10,
                                        next: null
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

const nthValueFromEnd = (node = linkList, k = 3) => {
    let link = node
    for(let i = 0; i < k; i++){
        link = link.next
    }
    while(link.next){
        link = link.next
        node= node.next
    }
    return node.value
}

  

posted @ 2023-01-30 20:35  671_MrSix  阅读(2)  评论(0编辑  收藏  举报