-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListCycleDetect2.cpp
More file actions
60 lines (57 loc) · 1.88 KB
/
linkedListCycleDetect2.cpp
File metadata and controls
60 lines (57 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//Given a linked list, return the node where the cycle begins. If there is no cycle, return null
/* Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
//Brute Force Approach :
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//hashSet to store every node of LL.
set<ListNode *> hashSet;
if(head==NULL)
return NULL;
while(head!=NULL)
{
//if current node is not present in hashSet then insert it
//else if it is already present then its the cycle node
if(!hashSet.count(head)){
hashSet.insert(head);
head=head->next;
}
else
return head;
}
return NULL;
}
};
//Optimal Approach :
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head==NULL || head->next==NULL)
return NULL;
//taking three pointers initially pointing head
ListNode *slow=head,*fast=head,*entry=head;
while(fast->next!=NULL && (fast->next)->next!=NULL)
{
//move slow by 1 node and fast by 2 node
//if there is aa cycle in LL then slow and fast must collide
slow=slow->next;
fast=(fast->next)->next;
if(fast==slow)
{
//the moment slow and fast collide we will start moving entry by 1 node from head ,and moving slow by 1 node
//the node on which slow and entry collide will be the starting point of cycle
while(entry!=slow){
entry=entry->next;
slow=slow->next;
}
return slow;
}
}
return NULL;
}
};