-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
101 lines (94 loc) · 2.76 KB
/
Solution.java
File metadata and controls
101 lines (94 loc) · 2.76 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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
// First find the meet point in the cycle.
ListNode fast, slow, meet = null, headA, headB;
fast = head;
slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
meet = slow;
break;
}
}
if (meet == null) {
return null;
}
// Seperate the list into two linkedLists
// Then the problem turns into a intersection.
// Set the beginning point of one linkedlist to headA.
headA = meet.next;
meet.next = null;
// Set another beginning point to headB.
headB = head;
fast = headA;
slow = headB;
if (headA == null || headB == null) {
return null;
}
int lenA = 0, lenB = 0, diff;
while (fast != null) {
lenA++;
fast = fast.next;
}
while (slow != null) {
lenB++;
slow = slow.next;
}
fast = headA;
slow = headB;
if (lenA > lenB) {
diff = lenA - lenB;
while (diff > 0) {
fast = fast.next;
diff--;
}
} else if (lenA < lenB) {
diff = lenB - lenA;
while(diff > 0) {
slow = slow.next;
diff--;
}
}
while (fast != null && slow != null) {
if (fast.val == slow.val) {
return fast;
}
fast = fast.next;
slow = slow.next;
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Solution s = new Solution();
ListNode dummy = s.new ListNode(0);
ListNode curr = s.new ListNode(0);
ListNode head = s.new ListNode(1);
head.next = s.new ListNode(2);
head.next.next = s.new ListNode(3);
head.next.next.next = s.new ListNode(4);
head.next.next.next.next = s.new ListNode(5);
head.next.next.next.next.next = s.new ListNode(6);
head.next.next.next.next.next.next = head.next.next;
dummy.next = head;
curr = dummy;
//System.out.println(isPalindrome(head));
//System.out.println(detectCycle(head).val);
System.out.println(curr == dummy);
}
}