Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
求連結串列是否有環的問題,要考慮連結串列為空的情況,定義一個快指標和一個慢指標,如果快指標和慢指標重合就表明有環
bool hasCycle(ListNode *head){ if(head == NULL || head->next == NULL) return false; ListNode* first = head, *second = head; while(second->next!=NULL && second->next->next!=NULL){ first = first->next; second = second->next->next; if(first == second) return true; } return false; }