I:
/**
* 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) return false;
ListNode *l1=head, *l2=head;
while (l1 && l1->next) {
l1=l1->next->next;
l2=l2->next;
if (l1==l2) {
return true;
}
}
return false;
}
};
II:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if (!head) return NULL;
int res=0;
ListNode *l1=head, *l2=head;
while(l1 && l1->next) {
l1=l1->next->next;
l2=l2->next;
if (l1==l2) {
res=1;
break;
}
}
if (res) {
l2=head;
while (l1!=l2) {
l1=l1->next;
l2=l2->next;
}
return l1;
}else {
return NULL;
}
}
};