Skip to content

Commit b4fabee

Browse files
committed
linked-list-cycle solution
1 parent 624eecf commit b4fabee

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

linked-list-cycle/yyyyyyyyyKim.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Definition for singly-linked list.
2+
# class ListNode:
3+
# def __init__(self, x):
4+
# self.val = x
5+
# self.next = None
6+
7+
class Solution:
8+
def hasCycle(self, head: Optional[ListNode]) -> bool:
9+
# 시간복잡도 O(n), 공간복잡도 O(n)
10+
# Follow up : 공간복잡도 O(1) 방식도 생각해 볼 것.
11+
12+
# 방문한 노드 set으로 저장
13+
visited = set()
14+
15+
while head:
16+
# 방문했던 노드라면 사이클 존재 -> True 리턴
17+
if head in visited:
18+
return True
19+
20+
visited.add(head) # 방문 노드로 저장
21+
head = head.next # 다음 노드로 이동
22+
23+
return False

0 commit comments

Comments
 (0)