Javascript中的8种常见数据结构(建议收藏)

开发 前端
堆栈遵循LIFO(后进先出)的原则。如果你把书堆叠起来,上面的书会比下面的书先拿。或者当你在网上浏览时,后退按钮会引导你到最近浏览的页面。

[[335977]]

1.Stack(栈)

 

堆栈遵循LIFO(后进先出)的原则。如果你把书堆叠起来,上面的书会比下面的书先拿。或者当你在网上浏览时,后退按钮会引导你到最近浏览的页面。

Stack具有以下常见方法:

  • push:输入一个新元素
  • pop:删除顶部元素,返回删除的元素
  • peek:返回顶部元素
  • length:返回堆栈中元素的数量

Javascript中的数组具有Stack的属性,但是我们使用 function Stack() 从头开始构建Stack

  1. function Stack() { 
  2.     this.count = 0; 
  3.   this.storage = {}; 
  4.  
  5.   this.push = function (value) { 
  6.     this.storage[this.count] = value; 
  7.     this.count++; 
  8.   } 
  9.  
  10.   this.pop = function () { 
  11.     if (this.count === 0) { 
  12.       return undefined; 
  13.     } 
  14.     this.count--; 
  15.     var result = this.storage[this.count]; 
  16.     delete this.storage[this.count]; 
  17.     return result; 
  18.   } 
  19.  
  20.   this.peek = function () { 
  21.     return this.storage[this.count - 1]; 
  22.   } 
  23.  
  24.   this.size = function () { 
  25.     return this.count
  26.   } 

2.Queue(队列)

 

Queue与Stack类似。唯一不同的是,Queue使用的是FIFO原则(先进先出)。换句话说,当你排队等候公交车时,队列中的第一个总是先上车。

队列具有以下方法:

  • enqueue:输入队列,在最后添加一个元素
  • dequeue:离开队列,删除前元素并返回
  • front:得到第一个元素
  • isEmpty:确定队列是否为空
  • size:获取队列中元素的数量

JavaScript中的数组具有Queue的某些属性,因此我们可以使用数组来构造Queue的示例:

  1. function Queue() { 
  2.   var collection = []; 
  3.   this.print = function () { 
  4.     console.log(collection); 
  5.   } 
  6.   this.enqueue = function (element) { 
  7.     collection.push(element); 
  8.   } 
  9.   this.dequeue = function () { 
  10.     return collection.shift(); 
  11.   } 
  12.   this.front = function () { 
  13.     return collection[0]; 
  14.   } 
  15.  
  16.   this.isEmpty = function () { 
  17.     return collection.length === 0; 
  18.   } 
  19.   this.size = function () { 
  20.     return collection.length; 
  21.   } 

优先队列

队列还有另一个高级版本。为每个元素分配优先级,并将根据优先级对它们进行排序:

  1. function PriorityQueue() { 
  2.  
  3.   ... 
  4.  
  5.   this.enqueue = function (element) { 
  6.     if (this.isEmpty()) { 
  7.       collection.push(element); 
  8.     } else { 
  9.       var added = false
  10.       for (var i = 0; i < collection.length; i++) { 
  11.         if (element[1] < collection[i][1]) { 
  12.           collection.splice(i, 0, element); 
  13.           added = true
  14.           break; 
  15.         } 
  16.       } 
  17.       if (!added) { 
  18.         collection.push(element); 
  19.       } 
  20.     } 
  21.   } 

测试一下:

  1. var pQ = new PriorityQueue(); 
  2. pQ.enqueue([ gannicus , 3]); 
  3. pQ.enqueue([ spartacus , 1]); 
  4. pQ.enqueue([ crixus , 2]); 
  5. pQ.enqueue([ oenomaus , 4]); 
  6. pQ.print(); 

返回

  1.   [  spartacus , 1 ], 
  2.   [  crixus , 2 ], 
  3.   [  gannicus , 3 ], 
  4.   [  oenomaus , 4 ] 

3. Linked List(链表)

 

从字面上看,链表是一个链式数据结构,每个节点由两个信息组成:节点的数据和指向下一个节点的指针。链表和传统数组都是线性数据结构,具有序列化的存储方式。当然,它们也有差异:

比较 Array Linked List
内存分配 静态内存分配,发生在编译和序列化过程中 动态内存分配,发生在运行过程中,非连续的。
获取元素 从索引中读取,速度更快 读取队列中的所有节点,直到得到特定的元素,速度较慢
添加/删除元素 由于是顺序记忆和静态记忆,速度较慢 由于是动态分配,只需要少量的内存开销,速度更快
空间结构 一维或多维 单边/双边,或循环链表

单边链表通常具有以下方法:

  • size:返回节点数
  • head:返回头部的元素
  • add:在尾部添加另一个节点
  • remove:删除某些节点
  • indexOf:返回节点的索引
  • elementAt:返回索引的节点
  • addAt:在特定索引处插入节点
  • removeAt:删除特定索引处的节点
  1. /** 链表中的节点 **/ 
  2. function Node(element) { 
  3.     // 节点中的数据 
  4.     this.element = element; 
  5.     // 指向下一个节点的指针 
  6.     this.next = null
  7. function LinkedList() { 
  8.   var length = 0; 
  9.   var head = null
  10.   this.size = function () { 
  11.     return length; 
  12.   } 
  13.   this.head = function () { 
  14.     return head; 
  15.   } 
  16.   this.add = function (element) { 
  17.     var node = new Node(element); 
  18.     if (head == null) { 
  19.       head = node; 
  20.     } else { 
  21.       var currentNode = head; 
  22.       while (currentNode.next) { 
  23.         currentNode = currentNode.next
  24.       } 
  25.       currentNode.next = node; 
  26.     } 
  27.     length++; 
  28.   } 
  29.   this.remove = function (element) { 
  30.     var currentNode = head; 
  31.     var previousNode; 
  32.     if (currentNode.element === element) { 
  33.       head = currentNode.next
  34.     } else { 
  35.       while (currentNode.element !== element) { 
  36.         previousNode = currentNode; 
  37.         currentNode = currentNode.next
  38.       } 
  39.       previousNode.next = currentNode.next
  40.     } 
  41.     length--; 
  42.   } 
  43.   this.isEmpty = function () { 
  44.     return length === 0; 
  45.   } 
  46.   this.indexOf = function (element) { 
  47.     var currentNode = head; 
  48.     var index = -1; 
  49.     while (currentNode) { 
  50.       index++; 
  51.       if (currentNode.element === element) { 
  52.         return index
  53.       } 
  54.       currentNode = currentNode.next
  55.     } 
  56.     return -1; 
  57.   } 
  58.   this.elementAt = function (index) { 
  59.     var currentNode = head; 
  60.     var count = 0; 
  61.     while (count < index) { 
  62.       count++; 
  63.       currentNode = currentNode.next
  64.     } 
  65.     return currentNode.element; 
  66.   } 
  67.   this.addAt = function (index, element) { 
  68.     var node = new Node(element); 
  69.     var currentNode = head; 
  70.     var previousNode; 
  71.     var currentIndex = 0; 
  72.     if (index > length) { 
  73.       return false
  74.     } 
  75.     if (index === 0) { 
  76.       node.next = currentNode; 
  77.       head = node; 
  78.     } else { 
  79.       while (currentIndex < index) { 
  80.         currentIndex++; 
  81.         previousNode = currentNode; 
  82.         currentNode = currentNode.next
  83.       } 
  84.       node.next = currentNode; 
  85.       previousNode.next = node; 
  86.     } 
  87.     length++; 
  88.   } 
  89.   this.removeAt = function (index) { 
  90.     var currentNode = head; 
  91.     var previousNode; 
  92.     var currentIndex = 0; 
  93.     if (index < 0 || index >= length) { 
  94.       return null
  95.     } 
  96.     if (index === 0) { 
  97.       head = currentIndex.next
  98.     } else { 
  99.       while (currentIndex < index) { 
  100.         currentIndex++; 
  101.         previousNode = currentNode; 
  102.         currentNode = currentNode.next
  103.       } 
  104.       previousNode.next = currentNode.next
  105.     } 
  106.     length--; 
  107.     return currentNode.element; 
  108.   } 

4. Set(集合)

 

集合是数学的基本概念:定义明确且不同的对象的集合。ES6引入了集合的概念,它与数组有一定程度的相似性。但是,集合不允许重复元素,也不会被索引。

一个典型的集合具有以下方法:

  • values:返回集合中的所有元素
  • size:返回元素个数
  • has:确定元素是否存在
  • add:将元素插入集合
  • remove:从集合中删除元素
  • union:返回两组交集
  • difference:返回两组的差
  • subset:确定某个集合是否是另一个集合的子集

为了区分ES6中的 set,我们在以下示例中声明为 MySet:

  1. function MySet() { 
  2.   var collection = []; 
  3.   this.has = function (element) { 
  4.     return (collection.indexOf(element) !== -1); 
  5.   } 
  6.   this.values = function () { 
  7.     return collection; 
  8.   } 
  9.   this.size = function () { 
  10.     return collection.length; 
  11.   } 
  12.   this.add = function (element) { 
  13.     if (!this.has(element)) { 
  14.       collection.push(element); 
  15.       return true
  16.     } 
  17.     return false
  18.   } 
  19.   this.remove = function (element) { 
  20.     if (this.has(element)) { 
  21.       index = collection.indexOf(element); 
  22.       collection.splice(index, 1); 
  23.       return true
  24.     } 
  25.     return false
  26.   } 
  27.   this.union = function (otherSet) { 
  28.     var unionSet = new MySet(); 
  29.     var firstSet = this.values(); 
  30.     var secondSet = otherSet.values(); 
  31.     firstSet.forEach(function (e) { 
  32.       unionSet.add(e); 
  33.     }); 
  34.     secondSet.forEach(function (e) { 
  35.       unionSet.add(e); 
  36.     }); 
  37.     return unionSet;  } 
  38.   this.intersection = function (otherSet) { 
  39.     var intersectionSet = new MySet(); 
  40.     var firstSet = this.values(); 
  41.     firstSet.forEach(function (e) { 
  42.       if (otherSet.has(e)) { 
  43.         intersectionSet.add(e); 
  44.       } 
  45.     }); 
  46.     return intersectionSet; 
  47.   } 
  48.   this.difference = function (otherSet) { 
  49.     var differenceSet = new MySet(); 
  50.     var firstSet = this.values(); 
  51.     firstSet.forEach(function (e) { 
  52.       if (!otherSet.has(e)) { 
  53.         differenceSet.add(e); 
  54.       } 
  55.     }); 
  56.     return differenceSet; 
  57.   } 
  58.   this.subset = function (otherSet) { 
  59.     var firstSet = this.values(); 
  60.     return firstSet.every(function (value) { 
  61.       return otherSet.has(value); 
  62.     }); 
  63.   } 

5. Hast table(哈希表)

 

哈希表是一种键值数据结构。由于通过键值查询的速度快如闪电,所以常用于Map、Dictionary或Object数据结构中。如上图所示,哈希表使用哈希函数(hash function)将键转换为数字列表,这些数字作为对应键的值。要快速使用键获取价值,时间复杂度可以达到O(1)。相同的键必须返回相同的值——这是哈希函数的基础。

哈希表具有以下方法:

  • add:添加键值对
  • remove:删除键值对
  • lookup:使用键查找对应的值

一个Javascript中简化的哈希表的例子:

  1. function hash(string, max) { 
  2.   var hash = 0; 
  3.   for (var i = 0; i < string.length; i++) { 
  4.     hash += string.charCodeAt(i); 
  5.   } 
  6.   return hash % max
  7.  
  8. function HashTable() { 
  9.   let storage = []; 
  10.   const storageLimit = 4; 
  11.  
  12.   this.add = function (key, value) { 
  13.     var index = hash(key, storageLimit); 
  14.     if (storage[index] === undefined) { 
  15.       storage[index] = [ 
  16.         [key, value] 
  17.       ]; 
  18.     } else { 
  19.       var inserted = false
  20.       for (var i = 0; i < storage[index].length; i++) { 
  21.         if (storage[index][i][0] === key) { 
  22.           storage[index][i][1] = value; 
  23.           inserted = true
  24.         } 
  25.       } 
  26.       if (inserted === false) { 
  27.         storage[index].push([key, value]); 
  28.       } 
  29.     } 
  30.   } 
  31.  
  32.   this.remove = function (key) { 
  33.     var index = hash(key, storageLimit); 
  34.     if (storage[index].length === 1 && storage[index][0][0] === key) { 
  35.       delete storage[index]; 
  36.     } else { 
  37.       for (var i = 0; i < storage[index]; i++) { 
  38.         if (storage[index][i][0] === key) { 
  39.           delete storage[index][i]; 
  40.         } 
  41.       } 
  42.     } 
  43.   } 
  44.  
  45.   this.lookup = function (key) { 
  46.     var index = hash(key, storageLimit); 
  47.     if (storage[index] === undefined) { 
  48.       return undefined; 
  49.     } else { 
  50.       for (var i = 0; i < storage[index].length; i++) { 
  51.         if (storage[index][i][0] === key) { 
  52.           return storage[index][i][1]; 
  53.         } 
  54.       } 
  55.     } 
  56.   } 

6. Tree(树)

 

Tree(树)数据结构是多层结构。与Array,Stack和Queue相比,它也是一种非线性数据结构。这种结构在插入和搜索操作时效率很高。我们来看看树型数据结构的一些概念。

  • root:树的根节点,无父节点
  • parent node:上层的直接节点,只有一个
  • child node:下层的直接节点可以有多个
  • siblings:共享同一个父节点
  • leaf:没有孩子的节点
  • Edge:节点之间的分支或链接
  • path:从起始节点到目标节点的边
  • Height of Nod:特定节点到叶节点的最长路径的边数
  • Height of Tree:根节点到叶节点的最长路径的边数
  • Depth of Node:从根节点到特定节点的边数
  • Degree of Node:子节点数

这里以二叉树为例。每个节点最多有两个节点,左边节点比当前节点小,右边节点比当前节点大。

 

二叉树中的常用方法:

  • add:将节点插入树
  • findMin:获取最小节点
  • findMax:获取最大节点
  • find:搜索特定节点
  • isPresent:确定某个节点的存在
  • remove:从树中删除节点

JavaScript中的示例:

  1. class Node { 
  2.   constructor(data, left = nullright = null) { 
  3.     this.data = data; 
  4.     this.left = left
  5.     this.right = right
  6.   } 
  7.  
  8. class BST { 
  9.   constructor() { 
  10.     this.root = null
  11.   } 
  12.  
  13.   add(data) { 
  14.     const node = this.root; 
  15.     if (node === null) { 
  16.       this.root = new Node(data); 
  17.       return
  18.     } else { 
  19.       const searchTree = function (node) { 
  20.         if (data < node.data) { 
  21.           if (node.left === null) { 
  22.             node.left = new Node(data); 
  23.             return
  24.           } else if (node.left !== null) { 
  25.             return searchTree(node.left); 
  26.           } 
  27.         } else if (data > node.data) { 
  28.           if (node.right === null) { 
  29.             node.right = new Node(data); 
  30.             return
  31.           } else if (node.right !== null) { 
  32.             return searchTree(node.right); 
  33.           } 
  34.         } else { 
  35.           return null
  36.         } 
  37.       }; 
  38.       return searchTree(node); 
  39.     } 
  40.   } 
  41.  
  42.   findMin() { 
  43.     let current = this.root; 
  44.     while (current.left !== null) { 
  45.       current = current.left
  46.     } 
  47.     return current.data; 
  48.   } 
  49.  
  50.   findMax() { 
  51.     let current = this.root; 
  52.     while (current.right !== null) { 
  53.       current = current.right
  54.     } 
  55.     return current.data; 
  56.   } 
  57.  
  58.   find(data) { 
  59.     let current = this.root; 
  60.     while (current.data !== data) { 
  61.       if (data < current.data) { 
  62.         current = current.left 
  63.       } else { 
  64.         current = current.right
  65.       } 
  66.       if (current === null) { 
  67.         return null
  68.       } 
  69.     } 
  70.     return current
  71.   } 
  72.  
  73.   isPresent(data) { 
  74.     let current = this.root; 
  75.     while (current) { 
  76.       if (data === current.data) { 
  77.         return true
  78.       } 
  79.       if (data < current.data) { 
  80.         current = current.left
  81.       } else { 
  82.         current = current.right
  83.       } 
  84.     } 
  85.     return false
  86.   } 
  87.  
  88.   remove(data) { 
  89.     const removeNode = function (node, data) { 
  90.       if (node == null) { 
  91.         return null
  92.       } 
  93.       if (data == node.data) { 
  94.         // no child node 
  95.         if (node.left == null && node.right == null) { 
  96.           return null
  97.         } 
  98.         // no left node 
  99.         if (node.left == null) { 
  100.           return node.right
  101.         } 
  102.         // no right node 
  103.         if (node.right == null) { 
  104.           return node.left
  105.         } 
  106.         // has 2 child nodes 
  107.         var tempNode = node.right
  108.         while (tempNode.left !== null) { 
  109.           tempNode = tempNode.left
  110.         } 
  111.         node.data = tempNode.data; 
  112.         node.right = removeNode(node.right, tempNode.data); 
  113.         return node; 
  114.       } else if (data < node.data) { 
  115.         node.left = removeNode(node.left, data); 
  116.         return node; 
  117.       } else { 
  118.         node.right = removeNode(node.right, data); 
  119.         return node; 
  120.       } 
  121.     } 
  122.     this.root = removeNode(this.root, data); 
  123.   } 

测试一下:

  1. const bst = new BST(); 
  2. bst.add(4); 
  3. bst.add(2); 
  4. bst.add(6); 
  5. bst.add(1); 
  6. bst.add(3); 
  7. bst.add(5); 
  8. bst.add(7); 
  9. bst.remove(4); 
  10. console.log(bst.findMin()); 
  11. console.log(bst.findMax()); 
  12. bst.remove(7); 
  13. console.log(bst.findMax()); 
  14. console.log(bst.isPresent(4)); 
  15.  
  16. false 

7. Trie (发音为 “try”)

 

Trie或“前缀树”也是搜索树的一种。Trie分步存储数据——树中的每个节点代表一个步骤。Trie是用来存储词汇的,所以它可以快速搜索,特别是自动完成功能。

Trie中的每个节点都有一个字母——分支之后可以组成一个完整的单词。它还包括一个布尔指示符,以显示这是否是最后一个字母。

Trie具有以下方法:

  • add:在字典树中插入一个单词
  • isWord:确定树是否由某些单词组成
  • print:返回树中的所有单词
  1. /** Node in Trie **/ 
  2. function Node() { 
  3.   this.keys = new Map(); 
  4.   this.end = false
  5.   this.setEnd = function () { 
  6.     this.end = true
  7.   }; 
  8.   this.isEnd = function () { 
  9.     return this.end
  10.   } 
  11.  
  12. function Trie() { 
  13.   this.root = new Node(); 
  14.   this.add = function (input, node = this.root) { 
  15.     if (input.length === 0) { 
  16.       node.setEnd(); 
  17.       return
  18.     } else if (!node.keys.has(input[0])) { 
  19.       node.keys.set(input[0], new Node()); 
  20.       return this.add(input.substr(1), node.keys.get(input[0])); 
  21.     } else { 
  22.       return this.add(input.substr(1), node.keys.get(input[0])); 
  23.     } 
  24.   } 
  25.   this.isWord = function (word) { 
  26.     let node = this.root; 
  27.     while (word.length > 1) { 
  28.       if (!node.keys.has(word[0])) { 
  29.         return false
  30.       } else { 
  31.         node = node.keys.get(word[0]); 
  32.         word = word.substr(1); 
  33.       } 
  34.     } 
  35.     return (node.keys.has(word) && node.keys.get(word).isEnd()) ? true : false
  36.   } 
  37.   this.print = function () { 
  38.     let words = new Array(); 
  39.     let search = function (node = this.root, string) { 
  40.       if (node.keys.size != 0) { 
  41.         for (let letter of node.keys.keys()) { 
  42.           search(node.keys.get(letter), string.concat(letter)); 
  43.         } 
  44.         if (node.isEnd()) { 
  45.           words.push(string); 
  46.         } 
  47.       } else { 
  48.         string.length > 0 ? words.push(string) : undefined; 
  49.         return
  50.       } 
  51.     }; 
  52.     search(this.root, new String()); 
  53.     return words.length > 0 ? words : null
  54.   } 

8. Graph(图)

 

Graph(有时称为网络)是指具有链接(或边)的节点集。根据联系是否有方向性,可以进一步分为两组(即定向图和不定向图)。Graph在我们的生活中被广泛使用——在导航应用中计算最佳路线,或者在社交媒体中推荐朋友,举两个例子。

图有两种表示形式:

邻接清单

在此方法中,我们在左侧列出所有可能的节点,并在右侧显示已连接的节点。

 

邻接矩阵

相邻矩阵以行和列的形式显示节点,行和列的交点诠释了节点之间的关系,0表示没有联系,1表示有联系,>1表示权重不同。

 

要查询图中的节点,必须用 “宽度优先搜索"(BFS)方法或 "深度优先搜索"(DFS)方法在整个树网中进行搜索。

让我们看一个例子的BFS在Javascript:

  1. function bfs(graph, root) { 
  2.   var nodesLen = {}; 
  3.   for (var i = 0; i < graph.length; i++) { 
  4.     nodesLen[i] = Infinity; 
  5.   } 
  6.   nodesLen[root] = 0; 
  7.   var queue = [root]; 
  8.   var current
  9.   while (queue.length != 0) { 
  10.     current = queue.shift(); 
  11.  
  12.     var curConnected = graph[current]; 
  13.     var neighborIdx = []; 
  14.     var idx = curConnected.indexOf(1); 
  15.     while (idx != -1) { 
  16.       neighborIdx.push(idx); 
  17.       idx = curConnected.indexOf(1, idx + 1); 
  18.     } 
  19.     for (var j = 0; j < neighborIdx.length; j++) { 
  20.       if (nodesLen[neighborIdx[j]] == Infinity) { 
  21.         nodesLen[neighborIdx[j]] = nodesLen[current] + 1; 
  22.         queue.push(neighborIdx[j]); 
  23.       } 
  24.     } 
  25.   } 
  26.   return nodesLen; 

测试一下:

  1. var graph = [ 
  2.   [0, 1, 1, 1, 0], 
  3.   [0, 0, 1, 0, 0], 
  4.   [1, 1, 0, 0, 0], 
  5.   [0, 0, 0, 1, 0], 
  6.   [0, 1, 0, 0, 0] 
  7. ]; 
  8. console.log(bfs(graph, 1)); 
  9.  
  10. // 结果 
  11.   0: 2, 
  12.   1: 0, 
  13.   2: 1, 
  14.   3: 3, 
  15.   4: Infinity 

就是这样——我们已经介绍了所有常见的数据结构,并给出了JavaScript中的例子。这应该能让你更好地了解数据结构在计算机中的工作原理。祝你编码愉快!

原文:https://medium.com/better-programming/8-common-data-structures-in-javascript-3d3537e69a27

 

作者:Kingsley Tan

本文转载自微信公众号「前端全栈开发者」,可以通过以下二维码关注。转载本文请联系前端全栈开发者公众号。

 

责任编辑:武晓燕 来源: 前端全栈开发者
相关推荐

2019-08-13 09:40:55

数据结构算法JavasCript

2019-10-29 08:59:16

Redis底层数据

2020-09-18 09:13:46

数据结构元素

2013-11-18 14:23:14

Json数据结构

2021-01-06 08:03:00

JavaScript数据结构

2020-08-31 14:30:47

Redis数据结构数据库

2019-08-01 11:27:46

数据复制数据源中间层

2021-01-28 07:33:34

JavaScript链表数据

2020-09-28 08:11:14

JavaScript数据

2019-09-03 10:40:23

数据结构HTML编程

2021-03-29 08:01:20

JavaScript数据结构

2018-03-20 13:28:16

数据结构堆栈算法

2019-04-03 05:04:50

2022-09-01 16:27:19

JavaScriptWeb开发

2024-02-19 16:23:11

2022-07-20 00:15:48

SQL数据库编程语言

2011-08-05 13:29:04

分页

2024-03-14 12:17:00

数据库数据模型

2020-03-04 11:10:14

数据结构程序员编译器

2018-03-14 10:51:00

数据库容灾技术
点赞
收藏

51CTO技术栈公众号