Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Idea: fast and slow pointer application. The speed pointer refers to the moving step, that is, the speed of moving forward each time. For example, you can move the fast pointer two times forward along the linked list and the slow pointer one time forward.
If the fast pointer reaches null, it means that the linked list ends with null without loops. If the fast pointer catches up with the slow pointer, it indicates there is a loop.
Time complexity O (N), space complexity O (1)
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 head;13 14 ListNode *slow = head, *fast = head;15 while (fast != NULL && fast->next != NULL) {16 fast = fast->next->next;17 slow = slow->next;18 if (fast == slow) return true;19 }20 21 return false;22 }23 };
[Leetcode] linked list cycle