вставить один узел в связанный список, давая мне циркуляр на следующем значении? - PullRequest
1 голос
/ 24 января 2020

вставка одного узла в связанный список, давая мне циркуляр на следующем значении !!

привет, я учусь создавать связанный список и тестировать его с шуткой, как вы можете видеть на фото мой проблема, что это не останавливается, из моего понимания это должно дать мне ноль в конце! вот так выглядит мой conole.log!

мой тестовый файл:

'use strict' ;


const LL = require('../lib/linked-list.js');


describe('Linked-List Test' , () => {

  it('Can properly insert into the linked list' , () => {
    let list = new LL() ;
    list.insert('test');
    expect(list.head.name).toEqual('test');
  });

});

my js file:

'use strict';

// const Node = require

function Node(value) {
  this.name = value;
  this.next = null;
}



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

  insert(value) {
    let node = new Node(value);
    if (!this.head) {
      this.head = node;
    }
    // { name : test1 , next = null }

    let pointer = this.head;
    console.log(pointer);
    console.log(pointer.next);
    while (pointer.next) {
      pointer = pointer.next;
    }
    console.log(node);
    pointer.next = node;
    console.log(pointer.next);
    console.log(pointer.next.next);
    console.log(pointer.next.next.next);
    console.log(pointer.next.next.next.next);

    return this;
  }


   


  include(value){

    let pointer = this.head;
    while (pointer.next) {
      if(pointer.next.name === value){
        return true ;
      }
      pointer = pointer.next;
    }

    return false ;
  }






}

module.exports = LinkedList;

1 Ответ

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

Попробуйте это. Вы должны добавить возврат в if (!this.head) состоянии. Поэтому он не должен выполнять код после этого блока.

"use strict";

// const Node = require

function Node(value) {
  this.name = value;
  this.next = null;
}

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

  insert(value) {
    let node = new Node(value);
    if (!this.head) {
      this.head = node;
      return this;
    }

    let pointer = this.head;
    while (pointer.next) {
      pointer = pointer.next;
    }

    pointer.next = node;
    return this;
  }

  include(value) {
    let pointer = this.head;
    while (pointer.next) {
      if (pointer.next.name === value) {
        return true;
      }
      pointer = pointer.next;
    }

    return false;
  }
}


let list = new LinkedList();
list.insert("test");
list.insert("test2");
console.log(list);
...