-
Notifications
You must be signed in to change notification settings - Fork 0
/
Find length of loop
98 lines (77 loc) · 2.21 KB
/
Find length of loop
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//Find length of loop
import java.io.*;
import java.util.*;
class Node {
int data;
Node next;
Node(int x) {
data = x;
next = null;
}
}
public class LinkedList {
public static void printList(Node node) {
while(node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
public static void makeLoop(Node head, Node tail, int x) {
if(x == 0) {
return;
}
Node curr = head;
for(int i = 1; i < x; i++) {
curr = curr.next;
}
tail.next = curr;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while(t-- > 0) {
ArrayList<Integer> arr = new ArrayList<>();
String input = br.readLine();
StringTokenizer st = new StringTokenizer(input);
while(st.hasMoreTokens()) {
arr.add(Integer.parseInt(st.nextToken()));
}
int k = Integer.parseInt(br.readLine());
Node head = new Node(arr.get(0));
Node tail = head;
for(int i = 1; i < arr.size(); ++i) {
tail.next = new Node(arr.get(i));
tail = tail.next;
}
makeLoop(head, tail, k);
Solution ob = new Solution();
System.out.println(ob.countNodesinLoop(head));
}
}
}
class Node {
int data;
Node next;
Node(int d) {data = d; next = null; }
}
class Solution {
public int countNodesinLoop(Node head) {
Node slowp = head;
Node fastp = head;
int count = 0;
while(fastp != null && fastp.next != null) {
slowp = slowp.next;
fastp = fastp.next.next;
if(slowp == fastp) {
count = 1;
while(slowp.next != fastp) {
count++;
slowp = slowp.next;
}
break;
}
}
return count;
}
}