思路:
floyed判环法。
https://www.youtube.com/watch?v=LUm2ABqAs1w
实现:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode 4 * { 5 * int val; 6 * ListNode *next; 7 * ListNode(int x) : val(x), next(NULL) {} 8 * }; 9 */ 10 class Solution 11 { 12 public: 13 bool hasCycle(ListNode *head) 14 { 15 if (!head) return false; 16 ListNode *p = head, *q = head; 17 while (p && q) 18 { 19 if (!p->next || !p->next->next) break; 20 p = p->next->next; 21 q = q->next; 22 if (p == q) return true; 23 } 24 return false; 25 } 26 }