Loading

linked-list-cycle (快慢指针判断是否有环)

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == NULL) return NULL;        //空表
        ListNode *slow = head;
        ListNode *fast = head;
        while (fast&&fast->next){
            slow = slow->next;    fast = fast->next->next;
            if (slow == fast)return true;            //相遇
        }
        return false;
    }
};

 

posted @ 2018-11-01 20:03  青山新雨  阅读(272)  评论(0)    收藏  举报