链表

链表是一种物理存储单元上非连续、非顺序的存储结构数据元素的逻辑顺序是通过链表中的指针链接次序实现的。链表由一系列结点(链表中每一个元素称为结点)组成,结点可以在运行时动态生成。每个结点包括两个部分:一个是存储数据元素的数据域,另一个是存储下一个结点地址的指针域。

链表允许插入和移除表上任意位置上的节点,但是不允许随机存取。链表有很多种不同的类型:单向链表双向链表以及循环链表。链表可以在多种编程语言中实现。

JS中的简单链表实现:

  1. class Node {
  2. constructor(element) {
  3. this.element = element;
  4. this.next = null;
  5. }
  6. }
  7. class LinkNodeList {
  8. constructor() {
  9. // 链表
  10. // 链表的第一个元素
  11. this.head = null;
  12. this.length = 0;
  13. }
  14. // 链表的相关操作
  15. // 增删改查
  16. // 增加
  17. append(element) {
  18. let node = new Node(element);
  19. let curr;
  20. // 两种情况:1.链表是空的 2.链表不是空的
  21. if (this.head == null) {
  22. // head是第一个
  23. this.head = node;
  24. } else {
  25. // 遍历链表
  26. curr = this.head;
  27. while (curr.next) {
  28. curr = curr.next;
  29. }
  30. curr.next = node;
  31. }
  32. this.length += 1;
  33. }
  34. removeAt(index) {
  35. let curr = this.head;
  36. let prev;
  37. let i = 0;
  38. if (index == 0) {
  39. // 删除第一项
  40. this.head = curr.next;
  41. } else {
  42. while (i < index) {
  43. prev = curr;
  44. curr = curr.next;
  45. i++;
  46. }
  47. prev.next = curr.next;
  48. // curr.next = null;
  49. }
  50. this.length -= 1;
  51. return curr.element;
  52. }
  53. print() {
  54. let curr = this.head;
  55. let ret = [];
  56. while (curr) {
  57. ret.push(curr.element);
  58. curr = curr.next;
  59. }
  60. console.log(ret.join('==>'));
  61. return ret.join('==>');
  62. }
  63. }
  64. let linkNode = new LinkNodeList();
  65. linkNode.append('哈喽');
  66. linkNode.append('你瞅啥');
  67. linkNode.append('嘿嘿');
  68. linkNode.append('瞅你咋的');
  69. linkNode.print();
  70. linkNode.removeAt(2);
  71. linkNode.print();

二叉树

二叉树特点是每个结点最多只能有两棵子树,且有左右之分。

三种遍历方式:

  • 前序遍历:自己 -> left -> right
  • 中序遍历:left -> 自己 -> right
  • 后序遍历:left -> right -> 自己

eg:

  1. 1
  2. / \
  3. 2 3
  4. / \ \
  5. 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。