Leetcode/cpp/141c.cpp
2024-06-21 01:36:27 +01:00

30 lines
850 B
C++

// https://leetcode.com/problems/linked-list-cycle/
/**
* Definition for singly-linked list.
*/
#include <cstddef>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Pursuing the cheeky logic from last time, indeed, we can run the loop 10001 times,
// and if the pointer still isn't at the end, we know it must be stuck in a loop
// (since the longest possible list is only 10000).
// This actually performs surprisingly well on the leaderboard, despite being totally, totally
// overkill for almost all the cases :)
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* ptr = head;
for (int i = 0; i < 10001; i++) {
if (ptr == nullptr) {
return false;
}
ptr = ptr->next;
}
return true;
}
};