leetcode -- 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?

[解题思路]

双指针问题,fast指针每次走两步,slow指针每次走一步,如果fast指针可以"追上"slow指针,则说明存在环

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         // IMPORTANT: Please reset any member data you declared, as
 4         // the same Solution instance will be reused for each test case.
 5         if(head == null){
 6             return false;
 7         }
 8         
 9         ListNode fast = head, slow = head;
10         while(fast.next != null && fast.next.next != null){
11             fast = fast.next.next;
12             slow = slow.next;
13             if(fast == slow){
14                 break;
15             }
16         }
17         return (fast.next == null || fast.next.next == null) ? false : true;
18     }
19 }

 

posted @ 2013-11-15 16:00  feiling  阅读(206)  评论(0编辑  收藏  举报