I tried this:
const reverseLinkedList = (head) => {
if (!head) {
return {
HEAD: null,
curr: null,
};
}
// Checking if current node is the last node or not
if (!head.next) {
let node = new Node(head.value);
return {
HEAD: node,
curr: node,
};
}
let { curr, HEAD } = reverseLinkedList(head.next);
curr.next = new Node(head.value);
return {
HEAD,
curr: curr.next,
};
};
let { HEAD } = reverseLinkedList(list.head);
console.log(HEAD);
And my Node class:
class Node {
constructor(val) {
this.value = val;
this.next = null;
}
}
here head is the main LinkedList's head, and HEAD is the head of new one. I'm using stack here. And the algorithm is in linear complexity.
Instead of creating new Node everytime, I think there is some better way to implement this.
Can you suggest some other ways?
Also is it possible to use queue here to achieve this?