|
2 | 2 |
|
3 | 3 | importcom.fishercoder.common.classes.ListNode;
|
4 | 4 |
|
5 |
| -/** |
6 |
| - * 142. Linked List Cycle II |
7 |
| -
|
8 |
| - Given a linked list, return the node where the cycle begins. If there is no cycle, return null. |
9 |
| -
|
10 |
| - Note: Do not modify the linked list. |
11 |
| -
|
12 |
| - Follow up: |
13 |
| - Can you solve it without using extra space? |
14 |
| - */ |
15 | 5 | publicclass_142 {
|
16 | 6 |
|
17 |
| -publicstaticclassSolution1 { |
18 |
| -publicListNodedetectCycle(ListNodehead) { |
19 |
| -ListNodeslow =head; |
20 |
| -ListNodefast =head; |
21 |
| -while (fast !=null &&fast.next !=null) { |
22 |
| -slow =slow.next; |
23 |
| -fast =fast.next.next; |
24 |
| -if (slow ==fast) { |
25 |
| -ListNodeslow2 =head; |
26 |
| -while (slow2 !=slow) { |
27 |
| -slow =slow.next; |
28 |
| -slow2 =slow2.next; |
29 |
| - } |
30 |
| -returnslow; |
| 7 | +publicstaticclassSolution1 { |
| 8 | +publicListNodedetectCycle(ListNodehead) { |
| 9 | +ListNodeslow =head; |
| 10 | +ListNodefast =head; |
| 11 | +while (fast !=null &&fast.next !=null) { |
| 12 | +slow =slow.next; |
| 13 | +fast =fast.next.next; |
| 14 | +if (slow ==fast) { |
| 15 | +ListNodeslow2 =head; |
| 16 | +while (slow2 !=slow) { |
| 17 | +slow =slow.next; |
| 18 | +slow2 =slow2.next; |
| 19 | + } |
| 20 | +returnslow; |
| 21 | + } |
| 22 | + } |
| 23 | +returnnull; |
31 | 24 | }
|
32 |
| - } |
33 |
| -returnnull; |
34 | 25 | }
|
35 |
| - } |
36 | 26 | }
|