diff options
| author | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
|---|---|---|
| committer | 3gg <3gg@shellblade.net> | 2025-02-05 18:36:31 -0800 |
| commit | 4689e4e80b479be25f7557d05818f5caa723aafa (patch) | |
| tree | 4df25811fe2a9a15b401375178da6537f4b6063f /top-interview-questions/easy/linked_list/06_linked_list_cycle.cc | |
Diffstat (limited to 'top-interview-questions/easy/linked_list/06_linked_list_cycle.cc')
| -rw-r--r-- | top-interview-questions/easy/linked_list/06_linked_list_cycle.cc | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/top-interview-questions/easy/linked_list/06_linked_list_cycle.cc b/top-interview-questions/easy/linked_list/06_linked_list_cycle.cc new file mode 100644 index 0000000..e8b4d1d --- /dev/null +++ b/top-interview-questions/easy/linked_list/06_linked_list_cycle.cc | |||
| @@ -0,0 +1,29 @@ | |||
| 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) return false; | ||
| 13 | if (!head->next) return false; | ||
| 14 | |||
| 15 | const ListNode* next1 = head; | ||
| 16 | const ListNode* next2 = head; | ||
| 17 | |||
| 18 | do { | ||
| 19 | next1 = next1->next; | ||
| 20 | next2 = next2->next; | ||
| 21 | if (next2) { | ||
| 22 | next2 = next2->next; | ||
| 23 | } | ||
| 24 | } | ||
| 25 | while ((next1 != head) && next1 && next2 && (next1 != next2)); | ||
| 26 | |||
| 27 | return next1 && next2 && (next1 == next2); | ||
| 28 | } | ||
| 29 | }; | ||
