数据结构学习 (持续更新...)

95 阅读2分钟

theme: cyanosis

1.栈是一种遵循先进先出的数据结构
2.栈的特点是只能在某一端添加删除操作,遵循先进后出原则
3.可以理解为一个空的罐子 第一个丢进罐子会压在最底下 要拿到第一个要把上面的全部取出

// 用js模拟一个栈
class Stack {
    stack = []
    push(item) {
        this.stack.push(item)
    }
    pop() {
        return this.stack.pop()
    }
    peek() {
        return this.stack[this.getSize() - 1]
    }
    getSize() {
        return this.stack.length
    }
    isEmpty() {
        return !!this.stack.length
    }
}

队列

1.队列是一种先进先出的数据结构
2.可以理解为 排队买东西 前面出 后面入

// 用js模拟一个队列
class Queue {
    queue = []
    enQueue(item) {
        this.queue.push(item)
    }
    deQueue() {
        return this.queue.shift()
    }
    getHeader() {
        return this.queue[0]
    }
    getSize() {
        return this.queue.length
    }
    isEmpty() {
        return this.getSize()
    }
}

链表

  1. 链表是一种线形结构 形像点说就是类似一个锁链 一环链这一环
  2. header -- item-next -- item-next -- item-next -- null
  3. 我的理解 就是类似简版原型链 通过一个属性链接起来
  // js 模拟一个链表
    class Node {
      constructor(v, next) {
        this.value = v
        this.next = next
      }
    }
    
    class LinkList {
      constructor(value) {
        this.initNode = new Node(value, null)
        this.size = 0
      }
      _find(v, index, cur) {
        if (index === cur) return v
        return this._find(v.next, index, cur + 1)
      }
      _checkIndex(index) {
        if (0 > index || index > this.size) throw new Error('index error')
      }
      addNode(v, index) {
        this._checkIndex(index)
        const prev = this._find(this.initNode, index, 0)
        prev.next = new Node(v, null)
        this.size++
      }
      removeNode(index) {
        this._checkIndex(index)
        const prev = this._find(this.initNode, index, 0)
        let prevNext = prev.next
        prev.next = prevNext.next
        this.size--
      }
      getNode(index) {
        this._checkIndex(index)
        return this._find(this.initNode, index, 0)
      }
      getSize() {
        return this.size
      }
      isEmpty() {
        return this.size === 0
      }
    }

二叉树

二叉树 是一种只有左右节点的一种数据结构

二叉树深度优先遍历  决定那一层先遍历
1.先序遍历
根左右
2.中序遍历
左根右
3.后序遍历
左右根


function deepTree(tree) {
    res.push(tree.val)
    tree.left && deepTree(tree.left)
    tree.right && deepTree(tree.right)
}


二叉树深度广度遍历  将同层数据全部收集在一起 加个变量记录当前层次
function forTree(tree, current) {
  if (!res[current]) res[current] = []
  res[current].push(tree.val)
  tree.left && deepTree(tree.left)
  tree.right && deepTree(tree.right)
}

Trie 树(前缀树)


前缀数 就是一层一层字母下来的树列如:

 app a ap
 
 a
 |
 p
 |
 p

合并集 实际就是说找到和自己相邻的亲戚

堆 分为最大堆 以及 最小堆 最大堆、最小堆顾名思义与他字面意思相同 大数在堆顶 小数在堆顶