leetcode-141-linked list cycle

Problem Description:

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

题目大意:

给定一个链表,判断它是否包含一个环

Solutions:

环链表的特征很多,最常用的判断方法是双指针法。让快慢两个指针同时在链表中遍历,如果存在环,那么两个指针一定会相遇。

Code in C++:

/**
 * 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) {
            if(!head||!head->next) return false;
            ListNode* fast=head->next;
            ListNode* slow=head;
            while(slow&&fast&&slow!=fast)
                {
                    if(fast->next)
                        fast=fast->next->next;
                    else return false;
                    slow=slow->next;
                }
            return slow==fast;

        }
};