【问题标题】:inserting single node to linked list giving me circular at the next value?将单个节点插入链表给我下一个值的循环?
【发布时间】:2020-01-24 12:28:54
【问题描述】:

将单个节点插入到链表中,给我下一个值的循环!

你好,我正在学习如何创建一个链表并用 jest 测试它, 正如您在照片中看到的那样,我的问题没有停止,据我了解,它应该在最后给我一个空值! this how my conole.log looks like !

我的测试文件:

'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');
  });

});

我的 js 文件:

'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;

【问题讨论】:

  • 您的 -> if (!this.head) { 可能需要返回,否则您稍后将在代码中添加到自己。

标签: javascript node.js linked-list insert jestjs


【解决方案1】:

试试这个。您必须在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);

【讨论】:

    猜你喜欢
    • 2016-09-24
    • 2023-03-24
    • 1970-01-01
    • 2014-11-01
    • 2016-12-19
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多