leetcode_linked_list_cycle 发表于 2016-11-30 难度:Easy 解题思路:两个节点slow、fast,slow每次走一步,fast每次走两步。如果有cycle,它们一定会相遇。 代码如下: 123456789101112131415161718192021222324252627/** * 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%