Linked List Cycle

来源:互联网 发布:apache 域名泛解析 编辑:程序博客网 时间:2024/05/16 19:12

使用快慢指针,如果两个指针在遍历的过程中相遇,则链表有环,否则无环。

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *fast = head, *slow = head;                while(fast && fast->next)        {            slow = slow->next;            fast = fast->next->next;            if(slow == fast)                return true;        }        return false;    }};

0 0