Add solution for cycle linked list

This commit is contained in:
pro100ton 2025-02-16 17:21:29 +03:00
parent 5cafe951db
commit b8d841ffac
2 changed files with 68 additions and 0 deletions

View file

@ -0,0 +1,35 @@
Linked List Cycle Detection
Given the beginning of a linked list head, return true if there is a cycle in the linked list. Otherwise, return false.
There is a cycle in a linked list if at least one node in the list that can be visited again by following the next pointer.
Internally, index determines the index of the beginning of the cycle, if it exists. The tail node of the list will set it's next pointer to the index-th node. If index = -1, then the tail node points to null and no cycle exists.
Note: index is not given to you as a parameter.
Example 1:
Input: head = [1,2,3,4], index = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:
Input: head = [1,2], index = -1
Output: false
Constraints:
1 <= Length of the list <= 1000.
-1000 <= Node.val <= 1000
index is -1 or a valid index in the linked list.
# Solution
## Использовать хэшмап
nodes = defaultdict()

View file

@ -0,0 +1,33 @@
from collections import defaultdict
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
nodes: set[ListNode] = set()
cur_node = head
while cur_node:
lb = len(nodes)
nodes.add(cur_node)
cur_node = cur_node.next
la = len(nodes)
if lb == la:
return True
return False
if __name__ == "__main__":
s = Solution()
e3 = ListNode(3, None)
e2 = ListNode(2, e3)
e1 = ListNode(1, e2)
e0 = ListNode(0, e1)
# k = [e0, e1, e2, e3]
nb = s.hasCycle(e0)
print(nb)