reverse a linked list javascript 1

reverse a linked list javascript

// O(n) time & O(n) space
function reverse(head) {
  if (!head || ! {
    return head;
  let tmp = reverse(; = head; = undefined;
  return tmp;

Here is what the above code is Doing:
1. If the list is empty or has only one node, return the head.
2. Otherwise, call reverse on the rest of the list.
3. Set the next node’s next pointer to the current node.
4. Set the current node’s next pointer to undefined.
5. Return the new head.

Similar Posts