“Algoritmo de lista vinculada JavaScript” Respostas de código

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

Respostas semelhantes a “Algoritmo de lista vinculada JavaScript”

Perguntas semelhantes a “Algoritmo de lista vinculada JavaScript”

Mais respostas relacionadas para “Algoritmo de lista vinculada JavaScript” em JavaScript

Procure respostas de código populares por idioma

Procurar outros idiomas de código