Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null){
walker = walker.next;
runner = runner.next.next;
if(walker ==runner) return true;
}
return false;
}
总结:cycle是圆圈不是循环的意思
public boolean hasCycle(ListNode head) {
ListNode p = head, pre = head;
while(p!=null&&p.next!=null){
if(p.next==head) return true;
p=p.next;
pre.next=head;
pre=p;
}
return false;
}
总结:人为断开所有已经判断过的连接。