I understand that there are a few reverse linked list questions using javascript, but I was hoping for more clarity on a solution that someone else had provided.
Is the use of a class LinkedList
necessary to declare a linkedlist or would just doing it like this example given work?
I'm just not clear as to how this function is just declaring a variable called reverseLinkedList
and solving it as opposed to actually using the class.
Not sure if that made any sense, but otherwise, would this solution be clear enough to solve the reversing a linked list problem?
Also, would this be considered a O(n) for time complexity? As it has a while loop that is set for a finite amount of time to run. And i'm not sure about space complexity.
// reverse a linked list
const reverseLinkedList = (linkedlist) => {
let node = linkedlist;
let previous = null;
while(node) {
// save next or you lose it!!!
let save = node.next;
// reverse pointer
node.next = previous;
// increment previous to current node
previous = node;
// increment node to next node or null at end of list
node = save;
}
return previous; // Change the list head !!!
}
linkedlist = reverseLinkedList(linkedlist);