[英]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.