프로그래밍/LeetCode
[LeetCode][Python3] 141. Linked List Cycle
snoopybox
2018. 9. 28. 00:41
Problem :
https://leetcode.com/problems/linked-list-cycle/description/
My Solution :
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
p1 = p2 = head
try:
while True:
p1 = p1.next
p2 = p2.next.next
if p1 is p2:
return True
except:
return False
Comment :
Cycle이 있으면 한번에 2칸 이동하는 녀석과 1칸 이동하는 녀석이 언젠가는 만나게 되어 있다. Cycle이 없으면 언젠가는 끝이 있고 p2 = p2.next.next에서 Exception이 발생할 수 밖에 없다. 코드가 깔끔하지는 않지만 그 2가지 특성만 이용해서 풀었다.