File tree Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Expand file tree Collapse file tree 1 file changed +87
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+
4
+ struct Node
5
+ {
6
+ int data;
7
+ Node* next;
8
+
9
+ Node (int val)
10
+ {
11
+ data = val;
12
+ next = NULL ;
13
+ }
14
+ };
15
+
16
+ void loopHere (Node* head, Node* tail, int position)
17
+ {
18
+ if (position==0 ) return ;
19
+
20
+ Node* walk = head;
21
+ for (int i=1 ; i<position; i++)
22
+ walk = walk->next ;
23
+ tail->next = walk;
24
+ }
25
+
26
+ bool detectLoop (Node* head);
27
+
28
+ int main ()
29
+ {
30
+ int t;
31
+ cin>>t;
32
+ while (t--)
33
+ {
34
+ int n, num;
35
+ cin>>n;
36
+
37
+ Node *head, *tail;
38
+ cin>> num;
39
+ head = tail = new Node (num);
40
+
41
+ for (int i=0 ; i<n-1 ; i++)
42
+ {
43
+ cin>> num;
44
+ tail->next = new Node (num);
45
+ tail = tail->next ;
46
+ }
47
+
48
+ int pos;
49
+ cin>> pos;
50
+ loopHere (head,tail,pos);
51
+
52
+ if ( detectLoop (head) )
53
+ cout<< " True\n " ;
54
+ else
55
+ cout<< " False\n " ;
56
+ }
57
+ return 0 ;
58
+ }
59
+ // } Driver Code Ends
60
+
61
+
62
+ /*
63
+
64
+ struct Node
65
+ {
66
+ int data;
67
+ struct Node *next;
68
+ Node(int x) {
69
+ data = x;
70
+ next = NULL;
71
+ }
72
+
73
+ */
74
+
75
+ bool detectLoop (Node* head)
76
+ {
77
+ // your code here
78
+ Node *slow=head,*fast=head;
79
+ while (fast!=NULL && fast->next !=NULL )
80
+ {
81
+ slow=slow->next ;
82
+ fast=fast->next ->next ;
83
+ if (slow==fast)
84
+ return 1 ;
85
+ }
86
+ return 0 ;
87
+ }
You can’t perform that action at this time.
0 commit comments