使用双指针技巧,判断链表中是否有环。
struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { if(head == NULL) return false; ListNode *s = head; ListNode *f = head; while(f->next != NULL){ f = f->next; if(f->next == NULL){ return false; } else{ f = f->next; s = s->next; if(f == s){ return true; } } } return false; } };
原文:https://www.cnblogs.com/olajennings/p/12459355.html