Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Note: The linked list loop is not the same as the tail pointer and header pointer, but may form a loop in the middle section. Therefore, you cannot only determine whether the element and the first element overlap.
Set two pointers: p_fast and p_slow. From the beginning, in the traversal chain table, p_fast takes two nodes each time, while p_slow takes one node each time. If there is a loop, the two pointers must overlap:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution {10 public:11 bool hasCycle(ListNode *head) {12 if(head == NULL) return false;13 14 ListNode *p_fast = head;15 ListNode *p_slow = head;16 17 do{18 p_slow = p_slow->next;19 if(p_fast != NULL)20 p_fast = p_fast->next;21 if(p_fast != NULL)22 p_fast = p_fast->next;23 else24 return false;25 }while(p_fast != p_slow);26 27 return true;28 29 }30 };
Linked List cycle: determines whether a linked list has a loop)