问题描述:
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?
解析:
网上解析很多,不一一赘述.
public ListNode detectCycle(ListNode head) {
if(head==null)
return null;
ListNode oneStep=head;
ListNode twoStep=head;
int step1 =0;
while(twoStep.next!=null&&twoStep.next.next!=null){
oneStep=oneStep.next;
twoStep=twoStep.next.next;
step1++;
if(twoStep==oneStep){
break;
}
}
if(!(twoStep.next!=null&&twoStep.next.next!=null))
return null;
else{
System.out.println(step1);
ListNode resultNode=head;
for(int i=0;i<step1;i++)
resultNode=resultNode.next;
while(true){
if(resultNode==head)
break;
resultNode=resultNode.next;
head=head.next;
}
return resultNode;
}
}