JavaScript数据结构与算法详解
一、数据结构
1、数组
2、栈
3、队列
4、链表
5、集合
// 封装集合的构造函数
function Set() {
// 使用一个对象来保存集合的元素
this.items = {}
// 集合的操作方法
// 判断集合中是否有某个元素
Set.prototype.has = function (value) {
return this.items.hasOwnProperty(value)
}
// 向集合中添加元素
Set.prototype.add = function (value) {
// 1.判断集合中是否已经包含了该元素
if (this.has(value)) return false
// 2.将元素添加到集合中
this.items[value] = value
return true
}
// 从集合中删除某个元素
Set.prototype.remove = function (value) {
// 1.判断集合中是否包含该元素
if (!this.has(value)) return false
// 2.包含该元素, 那么将元素删除
delete this.items[value]
return true
}
// 清空集合中所有的元素
Set.prototype.clear = function () {
this.items = {}
}
// 获取集合的大小
Set.prototype.size = function () {
return Object.keys(this.items).length
/*
考虑兼容性问题, 使用下面的代码
var count = 0
for (var value in this.items) {
if (this.items.hasOwnProperty(value)) {
count++
}
}
return count
*/
}
// 获取集合中所有的值
Set.prototype.values = function () {
return Object.keys(this.items)
/*
考虑兼容性问题, 使用下面的代码
var keys = []
for (var value in this.items) {
keys.push(value)
}
return keys
*/
}
// 集合间的操作
// 并集
Set.prototype.union = function (otherSet) {
// this: 集合对象A
// otherSet: 集合对象B
// 1.创建新的集合
var unionSet = new Set()
// 2.将A集合中所有的对象添加到新集合中
var values = this.values()
for (var i = 0; i < values.length; i++) {
unionSet.add(values[i])
}
// 3.取出B集合中的元素,判读断是否需要加到新集合
values = otherSet.values()
for (var i = 0; i < values.length; i++) {
unionSet.add(values[i])
}
return unionSet
}
// 交集
Set.prototype.intersection = function (otherSet) {
// this: 集合对象A
// otherSet: 集合对象B
// 1.创建新的集合
var intersectionSet = new Set()
// 2.从A中取出一个个元素,判断是否同时存在与集合B中,存在放入新集合中
var values = this.values
for (var i = 0; i < values.length; i++) {
var item = values[i]
if (otherSet.has(item)) {
intersectionSet.add(item)
}
}
//
return intersectionSet
}
// 差集
Set.prototype.difference = function(otherSet){
// this: 集合对象A
// otherSet: 集合对象B
// 1.创建新的集合
var differenceSet = new Set()
// 2.从A中取出一个个元素,判断是否同时存在与集合B中,不存在放入新集合中
var values = this.values
for (var i = 0; i < values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
differenceSet.add(item)
}
}
//
return differenceSet
}
// 子集
Set.prototype.sub = function(otherSet){
// this: 集合对象A
// otherSet: 集合对象B
// 遍历集合A中的所有元素,如果发现,集合A中的元素在集合B中不存在,返回false
// 如果遍历完了整个集合,依然没有返回false,那么返回true即可
var values = this.values
for (var i = 0; i < values.length; i++) {
var item = values[i]
if (!otherSet.has(item)) {
return false
}
}
//
return true
}
}
6、字典
7、哈希表
8、树
9、图
二、算法
1、排序
总结
good afternoon