-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListCycleII.java
More file actions
45 lines (40 loc) · 1.03 KB
/
LinkedListCycleII.java
File metadata and controls
45 lines (40 loc) · 1.03 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
import java.util.* ;
import java.io.*;
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public int data;
public Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
}
*****************************************************************/
public class Solution
{
public static Node firstNode(Node head)
{
// Write your code here.
Node fast = head;
Node slow = head;
while(fast!=null && fast.data!=-1 && fast.next!=null && fast.next.data!=-1){
fast = fast.next.next;
slow = slow.next;
if(slow==fast){
break;
}
}
if(fast==null || fast.data==-1 || fast.next==null || fast.next.data==-1){
return null;
}
Node temp = head;
while(temp!=slow){
slow = slow.next;
temp = temp.next;
}
return slow;
}
}