Reputation: 4544
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 ?
Upvotes: 0
Views: 2029
Reputation: 7631
I think first you have to define what it means to reverse a linked list with a loop. Let's assume you have a linked list:
1->2->3->4->5-|
^ |
|-------|
So if normally the list would print: 12345345345 if you keep traversing the cycle let's say the reversed linked list would mean all the arrows have reversed their direction and in reverse it should print 54354312
Now you can do something like this:
prev=head;
curr=head->next;
while !curr->visited && curr->next!=end
tmp=prev
prev=curr
curr=curr->next
prev->next=tmp
curr->visited=True
This is pseudo code and their may be small errors in the logic so don't copy verbatim but it's one basic idea.
Upvotes: 0
Reputation: 112366
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
stack:
init()
push(node)
pop() returns node
isIn(node) returns Boolean
and do something like
do
get next node
if node isIn stack
then
while stack not empty
pop node
break
else
push node in stack
fi
od
Upvotes: 4