Problem:
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Hide TagsLinked List Pointers
Thinking:
(1) If additional space can be opened, using Unordered_set to store traversed nodes, there is a ring structure when there is repetition.
(2) If the extra space is not applicable and the space complexity is O (1), use fast and slow double pointers. The slow pointer goes one step at a time, and the quick pointer goes two steps at a time.
If there is a ring structure, two pointers will always meet.
(3) Termination conditions should also be noted:
Fast!=null && Fast->next!=null
Prevent Fast->null->next from appearing
Code
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: bool Hascycle (ListNode *head) { ListNode *fast,*slow; if (head==null) return false; Slow=head; fast=head->next; while (Fast!=null && fast->next!=null) { if (slow==fast) return true; slow=slow->next; fast=fast->next->next; } return false; }};
Leetcode | | 141, Linked List Cycle