Как отобразить на консоли узлы из связанного списка - PullRequest
0 голосов
/ 26 января 2020

У меня есть класс, который создает список ссылок, а также функция, которая добавляет узлы в этот список. Я пытаюсь реализовать больше функций в списке, но я хочу увидеть изменения, которые эти функции вносят, отображая весь список.

это код:

function LinkedList() {
  var length = 0;
  var head = null;

  var Node = function(element) {
    this.element = element;
    this.next = null;
  };

  this.size = function() {
    return length;
  };

  this.head = function() {
    return head;
  };

  this.add = function(element) {
    var node = new Node(element);
    if (head === null) {
      head = node;
    } else {
      var currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
      }

      currentNode.next = node;
    }
    length++;
  };

После объявления LinkedList класс и добавление элементов с помощью функции class.add (element), как я могу отобразить весь список с помощью console.log ()?

Ответы [ 2 ]

0 голосов
/ 26 января 2020

Вы можете определить метод toString в prototype объекте и l oop через все элементы.

function LinkedList() {
  var length = 0;
  var head = null;

  var Node = function(element) {
    this.element = element;
    this.next = null;
  };

  this.size = function() {
    return length;
  };

  this.head = function() {
    return head;
  };

  this.add = function(element) {
    var node = new Node(element);
    if (head === null) {
      head = node;
    } else {
      var currentNode = head;

      while (currentNode.next) {
        currentNode = currentNode.next;
      }

      currentNode.next = node;
    }
    length++;
  };

}
LinkedList.prototype.toString = function() {
    let  head = this.head();
    let result = [];
    while(head) {
        result.push(head.element);
        console.log();
        head = head.next;
    }
    return result.join(", ");
}
let list = new LinkedList();
list.add("test");
list.add("test2");
list.add("test3");

console.log(list.toString());
0 голосов
/ 26 января 2020

Вам необходимо написать метод toString класса LinkedList. См .: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

...