141. Linked List Cycle
All prompts are owned by LeetCode. To view the prompt, click the title link above.
First completed : June 03, 2024
Last updated : July 01, 2024
Related Topics : Hash Table, Linked List, Two Pointers
Acceptance Rate : 50.586 %
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
visited = set()
if not head :
return False
currNode = head
while currNode.next :
visited.add(currNode)
currNode = currNode.next
if currNode in visited :
return True
return False
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
// Since no dynamic space and I don't feel like implementing a full datastructure,
// let's do a 2-pointer method
if (!head || !head->next) {
return false;
}
struct ListNode *one = head;
struct ListNode *two = head->next;
while (one != two) {
if (!two->next || !two->next->next) {
return false;
}
one = one->next;
two = two->next->next;
}
return true;
}