JavaScript实现链表printlist()方法打印结果为undefined问题求解
问题原因
你的代码打印undefined是几个逻辑错误共同导致的:
- 每个
Node实例里错误定义了this.head = null属性,调用n1.printlist()时,方法内取的this.head默认就是null,while循环完全不会执行 - 遍历起始节点写错:从头节点n1调用打印方法时,遍历的第一个节点应该是当前实例
this,而非不存在有效值的this.head - 调用
getNextNode()时多余传入了this.next参数,该方法本身无参,直接返回当前节点的next指向即可 printlist()方法没有设置返回值,外层执行console.log(n1.printlist())时,无返回值的函数默认返回undefined,就会打印出undefined- 额外逻辑瑕疵:你把
console.log(output)写在了循环内部,会逐次打印累加过程的中间字符串,不符合一次性打印完整链表的需求;同时head是链表级别的头指针,不应该挂载在每个独立节点上,节点只需要存自身数据和后继节点指针即可。
修复后的可运行代码
class Node { constructor(data) { this.data = data; this.next = null; } setNextNode(node) { this.next = node; } getNextNode() { return this.next; } printlist() { let current = this; let output = ""; while (current !== null) { output += current.data + ' '; current = current.getNextNode(); } return output.trim(); } } const n1 = new Node(1); const n2 = new Node(2); const n3 = new Node(3); n1.setNextNode(n2); n2.setNextNode(n3); console.log(n1.printlist()); // 运行输出: 1 2 3
内容的提问来源于stack exchange,提问作者Barun Bepart
相关产品推荐
相关产品推荐

