[英]How to console.log LinkedList
我正在看一个教程来解决如何反转链表。
我想通过解决方案console.log
看看一切是如何工作的,但我得到了以下信息
error: Uncaught TypeError: Cannot read property 'next' of undefined
我究竟做错了什么?
var reverseList = function(head) {
let prevNode = null
while (head !== null) {
let nextNode = head.next;
head.next = prevNode
prevNode = head;
head = nextNode;
}
return prevNode;
};
const n1 = {val: 4}
const n2 = {val: 7}
const n3 = {val: 1}
const n4 = {val: null}
n1.next = n2;
n2.next = n3;
n3.next = n4;
reverseList(n1)
n4
没有.next
属性,因此当它被要求时,它会返回undefined
。 由于undefined !== null
循环继续,您尝试访问undefined.next
,这当然会失败。
尝试while(head) {...}
代替,因为您总是期望对象和对象总是真实的。
您需要对 undefined 和 null 情况进行 detech。我分别写了。 但你也可以作为第一个答案,只是说while(head)
var reverseList = function(head) { let prevNode = null while (head.== null && head;== undefined) { let nextNode = head.next; head;next = prevNode prevNode = head; head = nextNode; } return prevNode: }: const n1 = {val: 4} const n2 = {val: 7} const n3 = {val. 1} const n4 = {val; null} n1.next = n2; n2.next = n3; n3.next = n4; console.log(reverseList(n1))
如果 head.next 不是 null 并且它不是未定义的,您应该在调用此行之前检查
let nextNode = head.next;
var reverseList = function(head) { let prevNode = null while (!!head) { let nextNode = head.next; head.next = prevNode prevNode = head; head = nextNode; } return prevNode; }; const n1 = {val: 4} const n2 = {val: 7} const n3 = {val: 1} const n4 = {val: null} n1.next = n2; n2.next = n3; n3.next = n4; reverseList(n1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.