西西弗西西弗
  • HTML 标签简介
  • CSS 属性简介
  • JavaScript 简介
  • JavaScript Promise 详细介绍
  • Vue.js 详细介绍
  • React 详细介绍
  • Node.js 详细介绍
数据结构与算法
  • HTML 标签简介
  • CSS 属性简介
  • JavaScript 简介
  • JavaScript Promise 详细介绍
  • Vue.js 详细介绍
  • React 详细介绍
  • Node.js 详细介绍
数据结构与算法

在 JavaScript 中实现数据结构和算法是一个涉及广泛主题的任务。由于篇幅限制,我将提供一些基本数据结构(如数组、链表、栈、队列、哈希表、二叉树)和相关算法的实现示例。这些示例将帮助你理解如何在 JavaScript 中操作这些数据结构。

数据结构

数组

JavaScript 中的数组是一种内置的数据结构,它可以用来存储元素集合。

let array = [1, 2, 3, 4, 5];
console.log(array.length); // 输出数组长度
array.push(6); // 在数组末尾添加元素
console.log(array); // 输出: [1, 2, 3, 4, 5, 6]

链表

链表是一种线性数据结构,其中每个元素(节点)都指向下一个元素。

class ListNode {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
  }

  append(value) {
    let newNode = new ListNode(value);
    if (!this.head) {
      this.head = newNode;
      return;
    }
    let current = this.head;
    while (current.next) {
      current = current.next;
    }
    current.next = newNode;
  }

  print() {
    let current = this.head;
    while (current) {
      console.log(current.value);
      current = current.next;
    }
  }
}

let linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.append(3);
linkedList.print(); // 输出: 1 2 3

栈

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

class Stack {
  constructor() {
    this.items = [];
  }

  push(element) {
    this.items.push(element);
  }

  pop() {
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}

let stack = new Stack();
stack.push(1);
stack.push(2);
console.log(stack.pop()); // 输出: 2
console.log(stack.peek()); // 输出: 1

队列

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

class Queue {
  constructor() {
    this.items = [];
  }

  enqueue(element) {
    this.items.push(element);
  }

  dequeue() {
    return this.items.shift();
  }

  peek() {
    return this.items[0];
  }

  isEmpty() {
    return this.items.length === 0;
  }
}

let queue = new Queue();
queue.enqueue(1);
queue.enqueue(2);
console.log(queue.dequeue()); // 输出: 1
console.log(queue.peek()); // 输出: 2

哈希表

哈希表是一种通过键值对存储数据的数据结构。

class HashTable {
  constructor() {
    this.table = [];
  }

  hash(key) {
    let hash = 0;
    for (let i = 0; i < key.length; i++) {
      hash = (hash + key.charCodeAt(i) * i) % 37;
    }
    return hash;
  }

  set(key, value) {
    let index = this.hash(key);
    if (!this.table[index]) {
      this.table[index] = {};
    }
    this.table[index][key] = value;
  }

  get(key) {
    let index = this.hash(key);
    if (this.table[index]) {
      return this.table[index][key];
    }
    return undefined;
  }
}

let hashTable = new HashTable();
hashTable.set("name", "John");
console.log(hashTable.get("name")); // 输出: John

二叉树

二叉树是每个节点最多有两个子节点的树结构。

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;
      return;
    }
    let current = this.root;
    while (true) {
      if (value < current.value) {
        if (!current.left) {
          current.left = newNode;
          return;
        }
        current = current.left;
      } else {
        if (!current.right) {
          current.right = newNode;
          return;
        }
        current = current.right;
      }
    }
  }

  // 其他二叉树操作,如遍历等...
}

let binaryTree = new BinaryTree();
binaryTree.insert(10);
binaryTree.insert(5);
binaryTree.insert(15);
// ...

算法

排序算法

冒泡排序

function bubbleSort(array) {
  let len = array.length;
  for (let i = 0; i < len; i++) {
    for (let j = 0; j < len - i - 1; j++) {
      if (array[j] > array[j + 1]) {
        let temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }
  return array;
}

let sortedArray = bubbleSort([3, 2, 5, 1, 4]);
console.log(sortedArray); // 输出: [1, 2, 3, 4, 5]

快速排序

function quickSort(array) {
  if (array.length < 2) {
    return array;
  }
  let pivot = array[0];
  let left = [];
  let right = [];
  for (let i = 1; i < array.length; i++) {
    if (array[i] < pivot) {
      left.push(array[i]);
    } else {
      right.push(array[i]);
    }
  }
  return [...quickSort(left), pivot, ...quickSort(right)];
}

let sortedArray = quickSort([3, 2, 5, 1, 4]);
console.log(sortedArray); // 输出: [1, 2, 3, 4, 5]

搜索算法

线性搜索

function linearSearch(array, value) {
  for (let i = 0; i < array.length; i++) {
    if (array[i] === value) {
      return i;
    }
  }
  return -1;
}

let index = linearSearch([3, 2, 5, 1, 4], 5);
console.log(index); // 输出: 2

二分搜索

function binarySearch(array, value) {
  let low = 0;
  let high = array.length - 1;
  while (low <= high) {
    let mid = Math.floor((low + high) / 2);
    if (array[mid] === value) {
      return mid;
    } else if (array[mid] < value) {
      low = mid + 1;
    } else {
      high = mid - 1;
    }
  }
  return -1;
}

let index = binarySearch([1, 2, 3, 4, 5], 4);
console.log(index); // 输出: 3

总结

数据结构和算法是计算机科学的基础,它们在解决实际问题时发挥着重要作用。在 JavaScript 中实现这些数据结构和算法可以帮助你更好地理解它们的原理,并提高你的编程技能。上述代码示例提供了一些基本的数据结构和算法实现,你可以在此基础上进行扩展和优化,以满足更复杂的需求。

Last Updated:
Contributors: Lee