leetcode 141. Linked List Cycle

来源:互联网 发布:java写代码用什么软件 编辑:程序博客网 时间:2024/05/05 01:51

思路跟leetcode 287. Find the Duplicate Number一样,都是

 Floyd's Algorithm的龟兔赛跑,不过这里只需要第一次相遇的结果,

 第一次相遇就说明有环,如果都到末尾了还不相遇就说明没有环。

struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};class Solution {public:    bool hasCycle(ListNode *head) {        if (head == NULL || head->next == NULL || head->next->next == NULL) {            return false;        }        ListNode *tortoise = head->next, *hare = head->next->next;        while (tortoise != hare && hare != NULL && hare->next != NULL) {            tortoise = tortoise->next;            hare = hare->next->next;        }        return hare != NULL && hare->next != NULL;    }};


0 0
原创粉丝点击