DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on • Edited on

Reverse Singly Linked List

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);
};
Enter fullscreen mode Exit fullscreen mode

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);

}
Enter fullscreen mode Exit fullscreen mode

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;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)