Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
In the Previous posts, we discussed several ways to find cycles in a list, starting from some O (n^2) trival solutions, to the classic Flyod's Cycle Finding Algorithm (also known as the Hare and Tortoise approach, or the 2 pointer approach) and a asymptotic faster variant, to a list reversal technique (which I havent seen being used anywhere). There are a few O(n lg n) solutions which I did not mentoin here. (If there is enought interest I will post this).
Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
There are several solutions to this problem. I already discussed a few soIutions prior to this. Lets look into an easy but not so commonly used solution.
Sol 5: Find Cycle through List Reversal
We've looked into some classic approaches of Linked List Cycle Finding Methods (Hare and Tortoise) in the previous posts. Lets see a more easier straightforward approach. I am a bit surprised this is not a usually used method.
Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
There are several solutions to this problem. I already discussed a couple of soIutions before. Lets look into more commonly used (classic) solutions
Sol 4: Two pointer approach (Faster)
In the last post we discussed about the regular two pointer approach and a bit about its background. Lets look into how we can make it a bit faster.
Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
There are several solutions to this problem. I already discussed a couple of soIutions before. Lets look into more commonly used (classic) solutions
Sol 3: Two pointer approach (Slow)
Q: Find whether or not there is a cylcle in a linked list? If so, Fix the cycle.
I will use the following code use in all (single) linked list programs:
struct LNode {
int data;
LNode* next;
LNode() {
next=NULL;
}
};
class LinkedList {
LNode* head;
}
For the sake of simplicity, I have put only an int field 'data' in the LNode struct. The LinkedList class currently only has a head pointer. I will add functions to it as we go along.