0

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?

4
  • Best not to use recursion, but if you have to there's this. Queues and stacks seem irrelevant to linked list algorithms, since LLs are lower-level data structures, usually used to implement such higher-level data structures. Commented Sep 15, 2022 at 5:35
  • Also is it possible to use queue here to achieve this Queue is First in first out, so doesn't seem relevant unless you are ok with algorithmic tweaks in there. However, there do exist iterative solution for this. Commented Sep 15, 2022 at 5:36
  • 1
    yeah got your point Commented Sep 15, 2022 at 5:37
  • 1
    yep, iterative one also worked well Commented Sep 15, 2022 at 13:30

1 Answer 1

2

If you wish to reverse the list iteratively, we

  • Capture current node's next node in some other temp variable.

  • Make current node's next point to previous node.

  • Store current Node as the previous one.

  • Move to next node with the help of temp node captured in 1st step.

  • Repeat from step 1 again.

Snippet:

const reverseLinkedList = (head) => {
  let temp = head, prev = null;

  while(temp != null){
    let nextNode = temp.next;
    temp.next = prev;
    prev = temp;
    temp = nextNode;
  }

   return prev; // as this is the new head
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.