Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
}*ListNode;
bool hasCycle(ListNode *head) {
ListNode *p1,*p2;
if(head==NULL||head->next==NULL) return false;
if(head->next==head) return true;
for(p1=p2=head;p1!=NULL&&p1->next!=NULL;){
p1=p1->next;
p1=p1->next;
p2=p2->next;
if(p1==p2) return true;
}
return false;
}