您的位置:首页 > 房产 > 建筑 > javascript常见数据结的构实现

javascript常见数据结的构实现

2025/3/10 10:10:19 来源:https://blog.csdn.net/m0_55049655/article/details/141505414  浏览:    关键词:javascript常见数据结的构实现

在JavaScript中,常见的数据结构实现包括数组、链表、栈、队列、哈希表(对象或Map)、集合(Set)、树(如二叉树)、图等。下面我将逐一简要介绍这些数据结构的基本实现。

1. 数组

JavaScript 的数组是动态的,可以自动调整大小。

let arr = [1, 2, 3];  
arr.push(4);  // 添加元素  
console.log(arr);  // 输出: [1, 2, 3, 4]

2. 链表

链表是一种在物理上非连续、非顺序的数据结构,数据元素的逻辑顺序是通过链表中的指针链接次序实现的。

class Node {  constructor(value) {  this.value = value;  this.next = null;  }  
}  class LinkedList {  constructor() {  this.head = null;  }  append(value) {  let newNode = new Node(value);  if (!this.head) {  this.head = newNode;  } else {  let current = this.head;  while (current.next) {  current = current.next;  }  current.next = newNode;  }  }  
}  let list = new LinkedList();  
list.append(1);  
list.append(2);

3. 栈

栈是一种后进先出(LIFO)的数据结构。

class Stack {  constructor() {  this.items = [];  }  push(element) {  this.items.push(element);  }  pop() {  if (this.items.length == 0)  return "Underflow";  return this.items.pop();  }  peek() {  return this.items[this.items.length - 1];  }  isEmpty() {  return this.items.length == 0;  }  size() {  return this.items.length;  }  
}  let stack = new Stack();  
stack.push(1);  
stack.push(2);  
console.log(stack.pop());  // 输出: 2

4. 队列

队列是一种先进先出(FIFO)的数据结构。

class Queue {  constructor() {  this.items = [];  }  enqueue(element) {  this.items.push(element);  }  dequeue() {  if (this.isEmpty())  return "Underflow";  return this.items.shift();  }  front() {  return this.items[0];  }  isEmpty() {  return this.items.length == 0;  }  size() {  return this.items.length;  }  
}  let queue = new Queue();  
queue.enqueue(1);  
queue.enqueue(2);  
console.log(queue.dequeue());  // 输出: 1

5. 哈希表

JavaScript 的对象或ES6中的Map可以充当哈希表。

let map = new Map();  
map.set('key', 'value');  
console.log(map.get('key'));  // 输出: value

6. 集合

JavaScript 的 Set 对象允许你存储任何类型的唯一值,无论是原始值还是对象引用。

let mySet = new Set();  
mySet.add(1);  
mySet.add(2);  
mySet.add(2);  // 2不会被再次添加  
console.log(mySet);  // 输出: Set(2) {1, 2}

7. 树

树是一种广泛使用的数据结构,模拟具有根节点和子节点的层次结构。

class TreeNode {  constructor(value) {  this.value = value;  this.left = null;  this.right = null;  }  
}  class BinaryTree {  constructor() {  this.root = null;  }  insert(value) {  let newNode = new TreeNode(value);  if (!this.root) {  this.root = newNode;  } else {  this.insertNode(this.root

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com