-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathT9.java
More file actions
47 lines (42 loc) · 1.16 KB
/
T9.java
File metadata and controls
47 lines (42 loc) · 1.16 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
package testCode;
public class T9 {
public static final void main(String args[]) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = head;
// head.next.next = new ListNode(3);
// head.next.next.next = head;
System.out.print(detectCycle(head).val);
}
public static ListNode detectCycle(ListNode head) {
if (null == head || null == head.next) {
return null;
}
if (head.next == head) {
return head;
}
ListNode tempNode = head.next;
head.next = null;
ListNode result = detectCycle(tempNode);
head.next = tempNode;
if (null == result) {
ListNode currentPtr = head.next;
while (null != currentPtr) {
if (currentPtr == head) {
result = head;
break;
}
currentPtr = currentPtr.next;
}
}
return result;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
}