简述4种数据结构

296 阅读1分钟

队列(queue)

特点:FIFO 先进先出

例如餐厅叫号,我们可以用这种数据结构

我们可以通过数组的 push 和 shift 来实现 队列


特点 : FILO 先进后出

例如代码执行时的 压栈 和 弹栈 就是 以栈的 FILO 形式执行的


链表

const createList = (value) => {
  return {
    data: value,
    next: null,
  };
};
//创建一个母链表

let appendList = (list, value) => {
  const node = {
    data: value,
    next: null,
  };
  list.next = node;
  return node;
};
//选择一个节点,加节点,形成链(只能往后加,不能在中间加)

const removeFromList = (list, node) => {
  let x = list;
  let p = node;
  while (x !== node && x !== null) {
    p = x;
    // 记住上一个节点,方便使上一个节点的next === node.next
    x = x.next;
  }
  if (x === null) {
    return false;
  }
  if (x === p) {
    p = x.next;
    return p;
  } else {
    p.next = node.next;
    return list;
  }
};

const travelList = (list, fn) => {
  let x = list;
  while (x !== null) {
    fn(x);
    x = x.next;
  }
};

哈希表

查看链接

哈希表的优化:

  1. 对 key 进行排序,使用二分法进行寻找
  2. 使用ASCII数字做索引,取余数进行寻找,若冲突则顺延

树(Tree)

const createTree = (value) => {
  return {
    data: value,
    children: null,
    parent: null,
  };
};
// 创建树

const addChild = (node, value) => {
  const newNode = {
    data: value,
    children: null,
    parent: node,
  };
  node.children = node.children || [];
  node.children.push(newNode);
  return newNode;
};

//创建树的各分支
const fn = (node) => {
  console.log(node.data);
};

const travelTree = (tree, fn) => {
  fn(tree);
  //对第一层print
  if (tree.children === null) {
    return;
  }
  //如果无next,什么都不做
  for (let i = 0; i < tree.children.length; i++) {
    travelTree(tree.children[i], fn);
  }
  //如果有next,对其进行递归
  return tree;
};
// 遍历children及children的children

const removeNode = (tree, node) => {
  const siblings = node.parent.children;
  //找到要删除节点的兄弟姐妹
  let index = 0;
  for (let i = 0; i < node.parent.children.length; i++) {
    if (node === siblings[i]) {
      index = i;
    }
    //获得要删除节点的index
  }
  siblings.splice(index, 1);
  return tree;
};