Recursion 1
var reverseList = function (head) {
let previous;
return reverse(head, (previous = null));
};
const reverse = (head, previous) => {
if (head === null) {
return previous;
}
let next = head.next;
head.next = previous;
return reverse(next, head);
};
Recursion 2
key point for below solution
-- at last we have to connect it to head for for that we will need head reference & we knw head.next & next of head can become head now.
var reverseList = function(head) {
const reverseR = (head) => {
if (head === null || head.next === null) {
return head;
}
let last = reverseR(head.next);
const rest_tail = head.next;
rest_tail.next = head;
head.next = null;
return last;
}
return reverseR(head);
}
Iterative
var reverseList = function (head) {
let current = head;
let previous = null;
while (current !== null) {
const tempNode = current.next;
current.next = previous;
previous = current;
current = tempNode;
}
return previous;
};
Top comments (0)