The queue

A queue is first in, first out

// queue.js
class Queue {
  constructor() {
    this.data = []
  }
  enqueue(element) { / / into the queue
    this.data.push(element)
  }
  dequeue() { / / out of the queue
    this.data.shift()
  }
  clear() { // Clear the queue
    this.data.length = 0
  }
  getLength() { // Queue length
    return this.data.length
  }
}
Copy the code

The stack

Stack is last in first out

// stack.js
class Stack {
  constructor() {
    this.data = []
  }
  push(element) { / / into the stack
    this.data.push(element)
  }
  pop() { / / out of the stack
    this.data.pop()
  }
  clear() { / / empty stack
    this.data.length = 0
  }
  getLength() { // Get the stack length
    return this.data.length
  }
}
Copy the code

Singly linked list

Linked lists make it easier to delete and add data! The head pointer points to the first stored element node, each node has a next attribute pointing to the next element node, and the last element pointer points to NULL

class Node {
  constructor(element) {
    this.element = element // What the node saves
    this.next = null // pointer to the next node}}class LinkList {
  constructor() {
    this.head = null // Table header, which points to the first node by default, null if not
    this.length = 0
  }
  append(element) { // Add a node
    const node = new Node(element)
    if (this.head === null)
      this.head = node
    else {
      let current = this.head
      while (current.next) {
        current = current.next
      }
      current.next = node // Find the last node and point next to the new node
    }
    this.length++
  }
  insert(position, elememt) { // Insert the node
    if (position >= 0 && position <= this.length) {
      const node = new Node(elememt)
      if (position === 0) {
        node.next = this.head
        this.head = node
      } else {
        let current = this.head
        let previous = null
        let index = 0
        // The list must start at the head
        while (index++ < position) {
          previous = current
          current = current.next
        }
        node.next = current
        previous.next = node
      }
      this.length++
    }
  }
  remove(position) { // Remove the node
    if (position > -1 && position < this.length) {
      if (position === 0) {
        this.head = this.head.next
      } else {
        let current = this.head
        let previous = null,
          index = 0
        while (index++ < position) {
          previous = current
          current = current.next
        }
        previous.next = current.next
      }
      this.length--
    }
  }
  update(position, element) { // Update the node content
    if (position > -1 && position < this.length) {
      let index = 0
      let current = this.head
      while (index++ < position) {
        current = current.next
      }
      current.element = element
    }
  }
}
Copy the code