xxxxxxxxxx
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
def has_cycle(head):
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
xxxxxxxxxx
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
xxxxxxxxxx
// my solution might look lengthy but go it is made in a way to give you idea about
// --making a linked list with a cycle and detecting it, using a beautiful easy algorithm.
//AIGHT bru, LESSGO!
#include<bits/stdc++.h>
using namespace std;
class node{
public:
int data;
node* next;
node(int val)
{
data=val;
next=NULL;
}
};//creating linked list.
void insertatend(node* head, int val)
{
node*n=new node(val);
if(head==NULL)
{
head=n;
return;
}
node* temp=head;
while(temp->next !=NULL)
{
temp=temp->next;
}
temp->next=n;
}
void makecycle(node* head, int pos)
{
node*temp=head;
int count=1;
node* supernode;
while(temp->next !=NULL)
{
if(count==pos){
supernode=temp;
}
temp=temp->next;
count++;
}
temp->next=supernode;
}//cycle has been made,
//NOW LETS TRY TO MAKE HARE AND RABBIT ALGORITHM OR FLOYD'S ALGORITHM TO DETECT A CYCLE IN A LINKED LIST
bool detectcycle(node* head)
{
node* slow= head;
node* fast= head;
while(fast!=NULL && fast->next !=NULL)
{
slow=slow->next;
fast=fast->next->next;
if(fast==slow) return true;
}
return false;
}
void display(node* head)
{
node*temp=head;
while(temp!=NULL)
{
cout<<temp->data<<"->";
temp=temp->next;
}
cout<<endl;
}
int main(){
node*head= new node(1);
insertatend(head,2);
insertatend(head,3);
insertatend(head,4);
insertatend(head,5);
insertatend(head,6);
// linked list has been made.
int pos;
cin>>pos;
display(head);
makecycle(head,pos);
if(detectcycle(head)) cout<<"yes";
else cout<<"no";
}