I'm looking at a tutorial to solve how to reverse a linked list.
I want to console.log
through the solution to see how everything works but I get the following
error: Uncaught TypeError: Cannot read property 'next' of undefined
What am I doing wrong?
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
does not have a .next
property, so when it gets asked for it it returns undefined
. Since undefined !== null
the loop continues and you try to access undefined.next
, which of course fails.
Try while(head) {...}
instead, as you're always expecting objects and objects will always be truthy.
you need to detech both undefined and null situations.I wrote seperately. But you can also do as first answer just say 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))
You should check before calling this line if head.next is not null and its not undefinned
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.