常见数据结构和Javascript实现总结

做前端的同学不少都是自学成才或者半路出家,计算机基础的知识比较薄弱,尤其是数据结构和算法这块,所以今天整理了一下常见的数据结构和对应的Javascript的实现,希望能帮助大家完善这方面的知识体系。

创新互联"三网合一"的企业建站思路。企业可建设拥有电脑版、微信版、手机版的企业网站。实现跨屏营销,产品发布一步更新,电脑网络+移动网络一网打尽,满足企业的营销需求!创新互联具备承接各种类型的成都网站制作、成都做网站、外贸营销网站建设项目的能力。经过十多年的努力的开拓,为不同行业的企事业单位提供了优质的服务,并获得了客户的一致好评。

1. Stack(栈)

Stack的特点是后进先出(last in first out)。生活中常见的Stack的例子比如一摞书,你最后放上去的那本你之后会最先拿走;又比如浏览器的访问历史,当点击返回按钮,最后访问的网站最先从历史记录中弹出。

  1. Stack一般具备以下方法:
  2. push:将一个元素推入栈顶
  3. pop:移除栈顶元素,并返回被移除的元素
  4. peek:返回栈顶元素
  5. length:返回栈中元素的个数

Javascript的Array天生具备了Stack的特性,但我们也可以从头实现一个 Stack类:

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

2. Queue(队列)

Queue和Stack有一些类似,不同的是Stack是先进后出,而Queue是先进先出。Queue在生活中的例子比如排队上公交,排在第一个的总是最先上车;又比如打印机的打印队列,排在前面的最先打印。

  • Queue一般具有以下常见方法:
  • enqueue:入列,向队列尾部增加一个元素
  • dequeue:出列,移除队列头部的一个元素并返回被移除的元素
  • front:获取队列的第一个元素
  • isEmpty:判断队列是否为空
  • size:获取队列中元素的个数

Javascript中的Array已经具备了Queue的一些特性,所以我们可以借助Array实现一个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.   this.isEmpty = function () {
  16.     return collection.length === 0;
  17.   }
  18.   this.size = function () {
  19.     return collection.length;
  20.   }
  21. }

Priority Queue(优先队列)

Queue还有个升级版本,给每个元素赋予优先级,优先级高的元素入列时将排到低优先级元素之前。区别主要是enqueue方法的实现:

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

测试一下:

 
 
 
 
  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. [
  2.   [ 'spartacus', 1 ],
  3.   [ 'crixus', 2 ],
  4.   [ 'gannicus', 3 ],
  5.   [ 'oenomaus', 4 ]
  6. ]

3. Linked List(链表)

顾名思义,链表是一种链式数据结构,链上的每个节点包含两种信息:节点本身的数据和指向下一个节点的指针。链表和传统的数组都是线性的数据结构,存储的都是一个序列的数据,但也有很多区别,如下表:

一个单向链表通常具有以下方法:

  1. size:返回链表中节点的个数
  2. head:返回链表中的头部元素
  3. add:向链表尾部增加一个节点
  4. remove:删除某个节点
  5. indexOf:返回某个节点的index
  6. elementAt:返回某个index处的节点
  7. addAt:在某个index处插入一个节点
  8. removeAt:删除某个index处的节点

单向链表的Javascript实现:

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

4. Set(集合)

集合是数学中的一个基本概念,表示具有某种特性的对象汇总成的集体。在ES6中也引入了集合类型Set,Set和Array有一定程度的相似,不同的是Set中不允许出现重复的元素而且是无序的。

一个典型的Set应该具有以下方法:

  1. values:返回集合中的所有元素
  2. size:返回集合中元素的个数
  3. has:判断集合中是否存在某个元素
  4. add:向集合中添加元素
  5. remove:从集合中移除某个元素
  6. union:返回两个集合的并集
  7. intersection:返回两个集合的交集
  8. difference:返回两个集合的差集
  9. subset:判断一个集合是否为另一个集合的子集

使用Javascript可以将Set进行如下实现,为了区别于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.   }
  39.   this.intersection = function (otherSet) {
  40.     var intersectionSet = new MySet();
  41.     var firstSet = this.values();
  42.     firstSet.forEach(function (e) {
  43.       if (otherSet.has(e)) {
  44.         intersectionSet.add(e);
  45.       }
  46.     });
  47.     return intersectionSet;
  48.   }
  49.   this.difference = function (otherSet) {
  50.     var differenceSet = new MySet();
  51.     var firstSet = this.values();
  52.     firstSet.forEach(function (e) {
  53.       if (!otherSet.has(e)) {
  54.         differenceSet.add(e);
  55.       }
  56.     });
  57.     return differenceSet;
  58.   }
  59.   this.subset = function (otherSet) {
  60.     var firstSet = this.values();
  61.     return firstSet.every(function (value) {
  62.       return otherSet.has(value);
  63.     });
  64.   }
  65. }

5. Hash Table(哈希表/散列表)

Hash Table是一种用于存储键值对(key value pair)的数据结构,因为Hash Table根据key查询value的速度很快,所以它常用于实现Map、Dictinary、Object等数据结构。如上图所示,Hash Table内部使用一个hash函数将传入的键转换成一串数字,而这串数字将作为键值对实际的key,通过这个key查询对应的value非常快,时间复杂度将达到O(1)。Hash函数要求相同输入对应的输出必须相等,而不同输入对应的输出必须不等,相当于对每对数据打上唯一的指纹。

一个Hash Table通常具有下列方法:

  1. add:增加一组键值对
  2. remove:删除一组键值对
  3. lookup:查找一个键对应的值

一个简易版本的Hash Table的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.   this.add = function (key, value) {
  12.     var index = hash(key, storageLimit);
  13.     if (storage[index] === undefined) {
  14.       storage[index] = [
  15.         [key, value]
  16.       ];
  17.     } else {
  18.       var inserted = false;
  19.       for (var i = 0; i < storage[index].length; i++) {
  20.         if (storage[index][i][0] === key) {
  21.           storage[index][i][1] = value;
  22.           inserted = true;
  23.         }
  24.       }
  25.       if (inserted === false) {
  26.         storage[index].push([key, value]);
  27.       }
  28.     }
  29.   }
  30.   this.remove = function (key) {
  31.     var index = hash(key, storageLimit);
  32.     if (storage[index].length === 1 && storage[index][0][0] === key) {
  33.       delete storage[index];
  34.     } else {
  35.       for (var i = 0; i < storage[index]; i++) {
  36.         if (storage[index][i][0] === key) {
  37.           delete storage[index][i];
  38.         }
  39.       }
  40.     }
  41.   }
  42.   this.lookup = function (key) {
  43.     var index = hash(key, storageLimit);
  44.     if (storage[index] === undefined) {
  45.       return undefined;
  46.     } else {
  47.       for (var i = 0; i < storage[index].length; i++) {
  48.         if (storage[index][i][0] === key) {
  49.           return storage[index][i][1];
  50.         }
  51.       }
  52.     }
  53.   }
  54. }

6. Tree(树)

顾名思义,Tree的数据结构和自然界中的树极其相似,有根、树枝、叶子,如上图所示。Tree是一种多层数据结构,与Array、Stack、Queue相比是一种非线性的数据结构,在进行插入和搜索操作时很高效。在描述一个Tree时经常会用到下列概念:

  1. Root(根):代表树的根节点,根节点没有父节点
  2. Parent Node(父节点):一个节点的直接上级节点,只有一个
  3. Child Node(子节点):一个节点的直接下级节点,可能有多个
  4. Siblings(兄弟节点):具有相同父节点的节点
  5. Leaf(叶节点):没有子节点的节点
  6. Edge(边):两个节点之间的连接线
  7. Path(路径):从源节点到目标节点的连续边
  8. Height of Node(节点的高度):表示节点与叶节点之间的最长路径上边的个数
  9. Height of Tree(树的高度):即根节点的高度
  10. Depth of Node(节点的深度):表示从根节点到该节点的边的个数
  11. Degree of Node(节点的度):表示子节点的个数

我们以二叉查找树为例,展示树在Javascript中的实现。在二叉查找树中,即每个节点最多只有两个子节点,而左侧子节点小于当前节点,而右侧子节点大于当前节点,如图所示:

一个二叉查找树应该具有以下常用方法:

  1. add:向树中插入一个节点
  2. findMin:查找树中最小的节点
  3. findMax:查找树中最大的节点
  4. find:查找树中的某个节点
  5. isPresent:判断某个节点在树中是否存在
  6. remove:移除树中的某个节点

以下是二叉查找树的Javascript实现:

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

测试一下:

 
 
 
 
  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));

打印结果:

 
 
 
 
  1. 1
  2. 7
  3. 6
  4. false

7. Trie(字典树,读音同try)

Trie也可以叫做Prefix Tree(前缀树),也是一种搜索树。Trie分步骤存储数据,树中的每个节点代表一个步骤,trie常用于存储单词以便快速查找,比如实现单词的自动完成功能。 Trie中的每个节点都包含一个单词的字母,跟着树的分支可以可以拼写出一个完整的单词,每个节点还包含一个布尔值表示该节点是否是单词的最后一个字母。

Trie一般有以下方法:

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

    新闻名称:常见数据结构和Javascript实现总结
    文章源于:http://www.hantingmc.com/qtweb/news27/119477.html

    网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

    广告

    声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联