本文主要介绍链表相关

链表这种数据结构的特点, 就是每一个节点对象通过一个next字段,链接下一个节点,所以总体看来, 就是一种链条的结构。

// 结构
    const listNode = function(val) {
        this.val = val
        this.next = null
    }

查找:时间复杂度O(n), 空间复杂度: O(1)
删除:时间复杂度O(n), 空间复杂度: O(1)

练练手:

1. 牛客BM1–链表反转

思路很清晰: 从头部节点遍历,挨个取出节点,暂存next节点。取出节点连接到新节点即可,最后返回。

let res
whiel(head) {
    const current = head
    const next = head.next
    current.next = res
    res = current
    head = next
}
return res

2. 返回倒数第k个元素

/*
 * function ListNode(x){
 *   this.val = x;
 *   this.next = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pHead ListNode类 
 * @param k int整型 
 * @return ListNode类
 */
function FindKthToTail( pHead ,  k ) {
    // write code here
    if (k === 0) return null
    let num = 0
    let start = pHead
    while (start) {
        num++
        start = start.next
    }
    let ji = 1
    while (pHead) {
        if (ji === num - k + 1 ) {
            const curNode = pHead
            return curNode
        }
        pHead = pHead.next
        ji++
    }
    console.log('here')
    return null
}
module.exports = {
    FindKthToTail : FindKthToTail
};
``