Linked List Cycle
Description:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Code:
1 bool hasCycle(ListNode *head) { 2 3 if (head == NULL) 4 return false; 5 ListNode* p = head; 6 ListNode* q = head; 7 8 while (p&&q) 9 { 10 p = p->next; 11 q = q->next; 12 if (p==NULL||q==NULL) 13 return false ; 14 q = q->next; 15 if (p==q) 16 return true; 17 } 18 return false; 19 }