Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Follow up: Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
ListNode nodeFast = head;
ListNode nodeSlow = head;
do {
if (nodeFast.next == null) {
return null;
}
nodeFast = nodeFast.next;
nodeSlow = nodeSlow.next;
if (nodeFast.next == null) {
return null;
}
nodeFast = nodeFast.next;
} while (nodeFast != nodeSlow);
nodeFast = head;
while (nodeFast != nodeSlow) {
nodeFast = nodeFast.next;
nodeSlow = nodeSlow.next;
}
return nodeSlow;
}
}
原文:http://www.cnblogs.com/rosending/p/5770123.html