File tree Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Expand file tree Collapse file tree 1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change 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+ };
You can’t perform that action at this time.
0 commit comments