JavaScript 链表

91 阅读1分钟
  • 多个元素组成的列表
  • 元素存储不连续,使用next指针连在一起

image.png

数组VS链表

  • 数组:增删非首位元素时需要移动元素
  • 链表:增删非首位元素时,不需要移动元素,只需要更改next指向即可
const a = {
  val:'a'
}
const b = {
  val:'b'
}
const c = {
  val:'c'
}
const d = {
  val:'d'
}
a.next=b.next=c.next=d

// 遍历链表
const p=a
while(p){    
  console.log(p.val) // a b c d    
  p=p.next
}

// c插入e链表
const e = {
  val:'e'
}
c.next=e
e.next=d

// 删除e
c.next=d

Leetcode 题库

原型链与链表

  • 原型链的本质是链表。
  • 原型链上的节点是各种原型对象,比如 Function.prototype, Object.prototype..
  • 原型链通过 proto 属性连接各种原型对象。

原型链长啥样?

  • obj -> Object.prototype -> null
  • func -> Function.prototype -> Object.prototype -> null
  • arr -> Array.prototype -> Object.prototype -> null

原型链知识点

  • 如果A沿着原型链能找到B.prototype,那么A instanceof B为true
  • 如果在A对象上没有找到x属性,那么会沿着原型链找x属性。

instanceof 原理及手写

  • 知识点:如果A沿着原型链能找到B.prototype,那么A instanceof B为true.
  • 解法:遍历A的原型链,如果找到B.prototype,返回 true,否则返回 false
const instanceOf = (A, B) => {
    let p = A;
    while (p) {
        if (p === B.prototype) return true;
        p = p.__proto__
    }
    return false;
}

使用链表指针获取JSON的节点值

根据json路径得出值

const json = {
    a: {
        b: {
            c: 1
        }
    },
    d: {
        e: 2
    }
}
const path = ['a', 'b', 'c'];

const getJSON = (path, json) => {
    let p = json;
    path.forEach(k => {
        p = p[k];
    });
    return p
}

getJSON(path, json) // 1