/**************************************************************************
*
* 141. [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle/)
*
* Given head, the head of a linked list, determine if the linked list has a cycle in it.
*
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
bool hasCycle(NODE *head) {
if (NULL == head)
return false;
NODE *fast = head;
NODE *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (fast == slow)
return true;
}
return false;
}
/**************************************************************************
*
* 142. [Linked List Cycle II](https://leetcode.com/problems/linked-list-cycle-ii/)
*
* Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
*
**************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode NODE;
NODE *detectCycle(NODE *head) {
if (NULL == head) return NULL;
NODE *fast = head;
NODE *slow = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
NODE *enter = head;
while (slow != enter) {
enter = enter->next;
slow = slow->next;
}
return enter;
}
}
return NULL;
}