Skip to content

Commit 1a2d3f1

Browse files
committed
feat: solve DaleStudy#225 with python
1 parent bfe247c commit 1a2d3f1

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

โ€Žlinked-list-cycle/EGON.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
from typing import Optional
2+
from unittest import TestCase, main
3+
4+
5+
# Definition for singly-linked list.
6+
class ListNode:
7+
def __init__(self, x):
8+
self.val = x
9+
self.next = None
10+
11+
12+
class Solution:
13+
def hasCycle(self, head: Optional[ListNode]) -> bool:
14+
return self.solve(head)
15+
16+
"""
17+
Runtime: 37 ms (Beats 93.02%)
18+
Time Complexity: O(n)
19+
> head๋ถ€ํ„ฐ next๊ฐ€ ์žˆ๋Š” ๋™์•ˆ ์„ ํ˜•์ ์œผ๋กœ ์กฐํšŒํ•˜๋ฏ€๋กœ O(n)
20+
21+
Memory: 18.62 (Beats 98.22%)
22+
Space Complexity: O(1)
23+
> head๋ฅผ ์ œ์™ธํ•˜๊ณ  ์•„๋ฌด ๋ณ€์ˆ˜๋„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•˜์œผ๋ฏ€๋กœ O(1)
24+
"""
25+
def solve(self, head: Optional[ListNode]) -> bool:
26+
if not head:
27+
return False
28+
29+
while head.next:
30+
if head.next and head.next.val is None:
31+
return True
32+
33+
head.val = None
34+
head = head.next
35+
36+
return False
37+
38+
39+
class _LeetCodeTestCases(TestCase):
40+
def test_1(self):
41+
head = None
42+
output = False
43+
self.assertEqual(Solution().hasCycle(head), output)
44+
45+
46+
if __name__ == '__main__':
47+
main()

0 commit comments

Comments
ย (0)