Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
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 || head.next == null || head.next.next == null){
return null;
}
ListNode p1 = head;
ListNode p2 = head.next.next;
while(p2 != null){
if(p1 == p2){
break;
}
p1 = p1.next;
if(p2.next == null || p2.next.next == null){
return null;
}
p2 = p2.next.next;
}
int circleLen = 0;//链长
do{
circleLen++;
p2 = p2.next;
}while(p1 != p2);
int c = 0;
p1 = head;
p2 = head;
while(c < circleLen){
c++;
p2 = p2.next;
}
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
Runtime: 396 ms