Linked List Cycle
Total Accepted: 3575 Total Submissions: 9771Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head==NULL || head->next==NULL) return false;
ListNode* p = head->next;
while(p!=NULL && p->next!=NULL) {
if(p==head || p->next==head) return true;
head = head->next;
p = p->next->next;
}
return false;
}
};