【数据结构与算法】3.链表

68 阅读1分钟

1.链表和数组的对比

  • 数组获取元素,只需要通过索引下标即可取出元素;而链表需要从头节点进行遍历
  • 数组增删非首尾元素需要进行大量的元素移动;而链表只需要修改 next 指针即可

2.链表的简单操作

const a = { val: "a" };
const b = { val: "b" };
const c = { val: "c" };
const d = { val: "d" };


a.next = b;
b.next = c;
c.next = d;

image.png

//遍历链表
let p = a;
while (p) {
  console.log(p.val);
  p = p.next;
}

image.png

//增加元素
const e = { val: "e" };


c.next = e;
e.next = d;

image.png

//删除元素
c.next = d;

image.png

3.链表的使用

  • 删除链表中的节点

image.png

 

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} node
 * @return {void} Do not return anything, modify node in-place instead.
 */
var deleteNode = function(node) {
    // 第一步:将需要删除节点的下个节点的值复制给当前节点 4 -> 1 -> 1 -> 9
    node.val = node.next.val
    // 第二步:当前节点的 next 指针指向下个节点的 next 指针指向的节点
    node.next = node.next.next
};
  • 原型链
//使用原型链实现 instanceof 原理
const myInstanceof = (A, B) => {
  const prototypeB = B.prototype;
  let p = A;
  while (p) {
    if (p === prototypeB) {
      return true;
    }
    p = p.__proto__;
  }
  return false;
};

image.png