How can we reverse a linked list if it has a loop (ie if the last node is is linked to a node in the middle) ?
Well, I saw that one of the solutions in here and hereto detect a loop in a linked list is to reverse it.
My doubt is – how is it possible to reverse a linked list,if you do not know where it ends. How can one even reverse a linked list that has a loop ?
Well, first, you’re going to need to define what “reverse” means in this context. Probably, what you need to do is
(1) find the link that makes it cyclic
(2) break that link
(3) then reverse the list somehow.
Doing it efficiently is going to mean finding some efficient way to identify the cycle. But if we assume a stack with an operation to tell if a node is already there, then you can just push the nodes onto a stack, checking until you give a link to a node you’ve already seen. Then pop the stack and voila you have the list in reverse order.
in pseudocode, you need a stack with an isIn operation
and do something like