链表
链表是一种物理存储单元上非连续、非顺序的存储结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。
链表允许插入和移除表上任意位置上的节点,但是不允许随机存取。链表有很多种不同的类型:单向链表,双向链表以及循环链表。链表可以在多种编程语言中实现。
JS中的简单链表实现:
class Node {constructor(element) {this.element = element;this.next = null;}}class LinkNodeList {constructor() {// 链表// 链表的第一个元素this.head = null;this.length = 0;}// 链表的相关操作// 增删改查// 增加append(element) {let node = new Node(element);let curr;// 两种情况:1.链表是空的 2.链表不是空的if (this.head == null) {// head是第一个this.head = node;} else {// 遍历链表curr = this.head;while (curr.next) {curr = curr.next;}curr.next = node;}this.length += 1;}removeAt(index) {let curr = this.head;let prev;let i = 0;if (index == 0) {// 删除第一项this.head = curr.next;} else {while (i < index) {prev = curr;curr = curr.next;i++;}prev.next = curr.next;// curr.next = null;}this.length -= 1;return curr.element;}print() {let curr = this.head;let ret = [];while (curr) {ret.push(curr.element);curr = curr.next;}console.log(ret.join('==>'));return ret.join('==>');}}let linkNode = new LinkNodeList();linkNode.append('哈喽');linkNode.append('你瞅啥');linkNode.append('嘿嘿');linkNode.append('瞅你咋的');linkNode.print();linkNode.removeAt(2);linkNode.print();
二叉树
二叉树特点是每个结点最多只能有两棵子树,且有左右之分。
三种遍历方式:
- 前序遍历:自己 -> left -> right
- 中序遍历:left -> 自己 -> right
- 后序遍历:left -> right -> 自己
eg:
1/ \2 3/ \ \4 5 6
前序遍历:1 => 2 => 4 => 5 => 3 => 6
中序遍历:4 => 2 => 5 => 1 => 6 => 3
后序遍历:4 => 5 => 2 => 6 => 3 => 1
备注:所有子文档中的 算法题 均来自于 leetcode。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/min-stack
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
