Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
69 lines (62 loc) · 1.27 KB

File metadata and controls

69 lines (62 loc) · 1.27 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
//program to check for loops and count them in the list
import java.io.*;
import java.util.*;
class LinkedList
{
static class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
}
static int count(Node n)
{
int tot=1;
Node temp = n;
while(temp.next != n)
{
tot++;
temp=temp.next;
}
return tot;
}
static int nodesinloop(Node no)
{
Node ptr1 = no, ptr2=no;
while(ptr1!=null && ptr2!=null && ptr2!=null)
{
ptr1 = ptr1.next; //moves a single node ahead
ptr2 = ptr2.next.next; //moves two nodes ahead
//if both meet at the same point then there is a loop
if(ptr1==ptr2)
{
return count(ptr1);
}
}
return 0;
}
static Node newnode(int element)
{
Node t = new Node(element);
return t;
}
public static void main(String argd[])
{
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);
head.next.next.next.next.next = newnode(6);
//we delibrately make a loop to test the code
head.next.next.next.next = head.next;
System.out.println(nodesinloop(head));
//let's try making another loop!
head.next.next.next.next.next = head.next;
System.out.println(nodesinloop(head));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.