Linked List Cycle

来源:互联网 发布:浙江省定额计价软件 编辑:程序博客网 时间:2024/06/06 01:54

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

经典的快慢指针

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


0 0