-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathLengthOfLoopInLinkedList.java
More file actions
77 lines (64 loc) · 1.5 KB
/
LengthOfLoopInLinkedList.java
File metadata and controls
77 lines (64 loc) · 1.5 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Java program to count number of nodes
// in loop in a linked list if loop is
// present
import java.io.*;
class GFG {
/* Link list node */
static class Node
{
int data;
Node next;
Node(int data)
{
this.data =data;
next =null;
}
}
// Returns count of nodes present in loop.
static int countNodes( Node n)
{
int res = 1;
Node temp = n;
while (temp.next != n)
{
res++;
temp = temp.next;
}
return res;
}
/* This function detects and counts loop
nodes in the list. If loop is not there
in then returns 0 */
static int countNodesinLoop( Node list)
{
Node slow_p = list, fast_p = list;
while (slow_p !=null && fast_p!=null && fast_p.next!=null)
{
slow_p = slow_p.next;
fast_p = fast_p.next.next;
/* If slow_p and fast_p meet at some point
then there is a loop */
if (slow_p == fast_p)
return countNodes(slow_p);
}
/* Return 0 to indeciate that ther is no loop*/
return 0;
}
static Node newNode(int key)
{
Node temp = new Node(key);
return temp;
}
/* Driver program to test above function*/
public static void main (String[] args) {
Node head = newNode(1);
head.next = newNode(2);
head.next.next = newNode(3);
head.next.next.next = newNode(4);
head.next.next.next.next = newNode(5);
/* Create a loop for testing */
head.next.next.next.next.next = head.next;
System.out.println( countNodesinLoop(head));
}
}
// This code is contributed by inder_verma.