
难度:Easy
解题思路:两个节点slow、fast,slow每次走一步,fast每次走两步。如果有cycle,它们一定会相遇。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
/** * 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 *dummy = new ListNode(-1); dummy->next = head; ListNode *slow = dummy; ListNode *fast = dummy; while(fast -> next != NULL && fast ->next -> next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) { return true; } } return false; } };
|
代码结果:9ms,超过53.73%
近期评论