Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

 

思路:模拟两个人沿着固定路线跑步,看先跑的人是否可以追上后跑的人

java代码:

  1. public boolean hasCycle(ListNode head) {
  2. if(head==null || head.next==null) return false;
  3. ListNode slow=head;
  4. ListNode fast = head;
  5. while(fast!=null && fast.next!=null) {  //注意判断边界条件
  6. slow=slow.next;
  7. fast=fast.next.next;
  8. // if(fast==null) return false;
  9. if(fast==slow) return true;
  10. }
  11. return false;
  12. }
posted @ 2014-07-19 23:15  purejade  阅读(58)  评论(0编辑  收藏  举报