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?

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
         if (head==null){
            return false;
        }
        ListNode pFast = head;
        ListNode pSlow = head;
        boolean first = true;
        while (pFast!=null){
            if (pSlow == pFast && !first) {
                return true;
            }
            pSlow = pSlow.next;
            if (pFast.next !=null) {
                pFast = pFast.next.next;
            } else {
                pFast = null;
            }
            first = false;
        }
        return false;
    }
}

 

posted @ 2014-01-06 11:37  23lalala  阅读(103)  评论(0编辑  收藏  举报