-
Notifications
You must be signed in to change notification settings - Fork 0
/
Has_loop.java
63 lines (57 loc) · 1.43 KB
/
Has_loop.java
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
public class Has_loop {
private Node head;
private Node tail;
private int length;
class Node{
int value;
Node next;
Node(int value){
this.value = value;
}
}
//print list
public void printList(){
Node temp = head;
while(temp!= null){
System.out.println(temp.value);
temp = temp.next;
}
}
//add element in the list
public void append(int value){
Node n = new Node(value);
if(length == 0){
head = n;
tail = n;
}
else{
tail.next = n;
tail = n;
}
length++;
}
// Implement a method called hasLoop that checks whether the list contains a loop or not.
// If the list contains a loop, the method should return true; otherwise, it should return false.
public boolean hasLoop(){
Node slow = head ;
Node fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow ){
return true;
}
}return false;
}
// getHead function to return head
public Node getHead(){
return head;
}
//constructor
Has_loop(int value){
Node newNode = new Node(value);
head = newNode;
tail = newNode;
length= 1;
}
}