判断一个链表是否有循环,如果有返回第一相遇节点,否则返回NULL。
解题思路也是前面的龟兔赛跑问题,只不过问题变成了找循环的第一个节点。
解题如下:
/**
* 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) {
ListNode oneStep = head;
ListNode twoStep = head;
boolean cycle = false;
while(oneStep != null && twoStep != null && twoStep.next != null){
oneStep = oneStep.next;
twoStep = twoStep.next.next;
if(oneStep == twoStep) {
cycle = true;
break;
}
}
if(!cycle) return null;
oneStep = head;
while(twoStep != oneStep){
oneStep = oneStep.next;
twoStep = twoStep.next;
}
return twoStep;
}
}