Skip to content

Commit 5814fd6

Browse files
committed
leetcode 142
1 parent b88bcc8 commit 5814fd6

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/*
2+
written by Pankaj Kumar.
3+
country:-INDIA
4+
*/
5+
typedef long long ll ;
6+
const ll INF=1e18;
7+
const ll mod1=1e9+7;
8+
const ll mod2=998244353;
9+
//Add main code here
10+
11+
/**
12+
* Definition for singly-linked list.
13+
* struct ListNode {
14+
* int val;
15+
* ListNode *next;
16+
* ListNode(int x) : val(x), next(NULL) {}
17+
* };
18+
*/
19+
class Solution
20+
{
21+
public:
22+
ListNode *detectCycle(ListNode *head)
23+
{
24+
// method 1
25+
ListNode *slow = head, *fast = head;
26+
27+
while (fast != NULL && fast->next != NULL)
28+
{
29+
slow = slow->next;
30+
fast = fast->next->next;
31+
if(slow == fast){
32+
slow = head;
33+
while(slow != fast){
34+
slow = slow->next;
35+
fast = fast->next;
36+
}
37+
return slow;
38+
}
39+
}
40+
return NULL;
41+
42+
// method 2
43+
ListNode *temp = head;
44+
unordered_map<ListNode *, int> m;
45+
while (temp != NULL)
46+
{
47+
if (m.find(temp) != m.end())
48+
{
49+
return temp;
50+
}
51+
m[temp]++;
52+
temp = temp->next;
53+
}
54+
return NULL;
55+
}
56+
};

0 commit comments

Comments
 (0)