-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedListCycle2.java
57 lines (50 loc) · 1.67 KB
/
LinkedListCycle2.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
/****************************************************************
Following is the class structure of the Node class:
class Node {
public int data;
public Node next;
Node()
{
this.data = 0;
this.next = null;
}
Node(int data)
{
this.data = data;
this.next = null;
}
Node(int data, Node next)
{
this.data = data;
this.next = next;
}
}
*****************************************************************/
public class Solution {
public static Node firstNode(Node head) {
// Write your code here.
// Initialize two pointers, slow and fast, to the head of the linked list.
Node slow = head;
Node fast = head;
// Move the slow pointer one step and the fast pointer two steps at a time through the linked list,
// until they either meet or the fast pointer reaches the end of the list.
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
// If the pointers meet, there is a cycle in the linked list.
// Reset the slow pointer to the head of the linked list, and move both pointers one step at a time
// until they meet again. The node where they meet is the starting point of the cycle.
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}
// If the fast pointer reaches the end of the list without meeting the slow pointer,
// there is no cycle in the linked list. Return null.
return null;
}
}