“Algoritmo de lista vinculada JavaScript” Código de respuesta

Lista vinculada JavaScript

// Linked Lists of nodes
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

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

  // Add a value at beginning of list
  addStart(value) {
    const node = new Node(value);
    node.next = this.head;
    this.head = node;
  }

  // Add a value at end of list
  addEnd(value) {
    const node = new Node(value);
    let curr = this.head;
    if (curr == null) {
      this.head = node;
      return;
    }

    while (curr !== null && curr.next !== null) {
      curr = curr.next;
    }

    curr.next = node;
  }
}

const list = new LinkedList();
list.addStart(1);
list.addStart(2);
list.addEnd(3);

console.log(list.head.value); // 2 (head of list)
Wissam

Algoritmo de lista vinculada JavaScript

// Linked Lists of nodes
class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

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

  // Add a value at beginning of list
  addStart(value) {
    const node = new Node(value);
    node.next = this.head;
    this.head = node;
  }

  // Add a value at end of list
  addEnd(value) {
    const node = new Node(value);
    let curr = this.head;
    if (curr == null) {
      this.head = node;
      return;
    }

    while (curr !== null && curr.next !== null) {
      curr = curr.next;
    }

    curr.next = node;
  }

  // return the size of the link list
  size() {
    let count = 0;
    const node = this.head;
    if (!node) return count;
    while (node) {
      count++;
      node = node.next;
    }
    return count;
  }

  // empty the node
  clear() {
    this.head = null;
  }

  getFirst() {
    return this.head;
  }

  getLast() {
    let lastNode = this.head;
    if (lastNode) {
      while (lastNode.lastNode) {
        lastNode = lastNode.next;
      }
    }
    return lastNode;
  }
}

const list = new LinkedList();
list.addStart(1);
list.addStart(2);
list.addEnd(3);

console.log(list.head.value); // 2 (head of list)
Godbless Onoriode

Respuestas similares a “Algoritmo de lista vinculada JavaScript”

Preguntas similares a “Algoritmo de lista vinculada JavaScript”

Más respuestas relacionadas con “Algoritmo de lista vinculada JavaScript” en JavaScript

Explore las respuestas de código populares por idioma

Explorar otros lenguajes de código