141. Linked List Cycle

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

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *pFast = head;
        ListNode *pSlow = head;
        while(pSlow!=NULL&&pFast!=NULL&&pFast->next!=NULL){
            pSlow = pSlow->next;
            pFast = pFast->next->next;
            if(pSlow==pFast)
                return true;
        }
        return false;
    }
};

 

posted on 2017-03-04 22:45  123_123  阅读(62)  评论(0编辑  收藏  举报