JavaScript链接列表:方法removeHead()和contains()不起作用

时间:2017-10-10 20:53:43

标签: javascript node.js npm linter

使用ES6样式,任务是构建一个链表并通过npm linter测试传递它。这是我写的代码:

StudentProperties

这是linting错误:

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    // Do not modify anything inside of the constructor
  }
  // Wraps the given value in a node object and adds the node to the tail of the list
  // If the list is empty, the new element is considered the tail as 
well as the head
  // If there is one element in the list before the new element is added, the new element becomes the tail of the list
  addToTail(value) {
    const newNode = {
      value,
      next: null
    };
    if (!(this.head) && !(this.tail)) {
      this.head = newNode;
      this.tail = newNode;
    } else this.tail = newNode;
  }
  // Removes the current head node from the list, replacing it with the next element in the list
  // Returns the value of the removed node
  removeHead() {
    const removedHead = this.head.value;
    this.head = this.head.next;
    return removedHead;
  }
  // Checks the linked list for the given value
  // Returns true if the the value is found in the list, false otherwise
  contains(value) {
    let found = false;
    let checkedNode = this.head;
    while (checkedNode) {
      if (checkedNode.value === value) {
        found = true;
      }
      checkedNode = checkedNode.next;
    } return found;
  }
}

这是测试它的文件:

● LinkedList › should remove head when removeHead is invoked

    TypeError: Cannot read property 'value' of null

      at Object.<anonymous> (tests/linked-list.test.js:48:21)

  LinkedList
    ✓ should have the methods "addToTail", "removeHead", and "contains" (5ms)
    ✓ should update the tail value when a new node is added (2ms)
    ✓ should keep the same head after adding nodes (2ms)
    ✕ should return true from contains if a matching value is found and false otherwise (4ms)
    ✕ should remove head when removeHead is invoked (2ms)
    ✓ should return the head that is removed when removeHead is invoked (1ms)
    ✓ should not contain removed values (1ms)

唯一的两个错误是没有删除头部并且没有返回正确的布尔值。我不知道为什么。

1 个答案:

答案 0 :(得分:2)

插入新元素时,永远不会设置next引用。

请改为尝试:

if (!(this.head) && !(this.tail)) {
  this.head = newNode;
  this.tail = newNode;
} else {
    this.tail.next = newNode;
    this.tail = newNode;
}