# Linked List Cycle II in C++

Consider we have a linked list, and we have to check whether there is any cycle or not. To represent the cycle in the given linked list, we will use one integer pointer called pos. This pos represents a position in the linked list where tail is connected. So if pos is -1, then there is no cycle present in the linked list. For example, the linked list is like [5, 3, 2, 0, -4, 7], and pos = 1. So there is a cycle, and tail is connected to the second node. The constraint is that we cannot modify the list

To solve this, we will follow these steps −

• while slow, fast and next of fast is available, then
• slow := next of slow
• fast := next of (next of fast)
• if slow = fast, then break
• if fast is not empty or next of first is not empty, then return null
• if slow = fast, then
• while slow is not same as fast
• slow := next of slow and fast := next of fast
• return slow

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
if(pos != -1){
int p = 0;
while(p < pos){
ptr = ptr->next;
p++;
}
return ptr;
}
return NULL;
}
class Solution {
public:
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;
if(slow == fast)break;
}
if(!fast || !fast->next)return NULL;
if(slow == fast){
while(slow!=fast){
slow = slow->next;
fast = fast->next;
}
}
return slow;
}
};
main(){
Solution ob;
vector<int> v = {5,3,2,0,-4,7};
int pos = 1;
ListNode *lastNode = get_node(head, v.size() - 1);
cout << "Tail is connected to the node with value:" <<ob.detectCycle(head)->val;
}

## Input

[5,3,2,0,-4,7]
1

## Output

Tail is connected to the node with value:3

Updated on: 04-May-2020

196 Views