判断单链表是否有环

    科技2022-07-20  121

    判断单链表是否有环(快慢指针法——>最优)

    //假定有头节点 bool hasCycle(LinkNode* head ) { // write code here // LinkNode *p=head->next; if(head == NULL) return 0; LinkNode *slow = head; LinkNode *fast = head; while(fast != NULL && fast->next != NULL){ slow = slow->next; fast = fast->next->next; if(slow == fast){ return 1; } } return 0; }
    Processed: 0.011, SQL: 8