【发布时间】: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