작심삼일

[LeetCode] 141 | Linked List Cycle | Python 본문

스터디/코테

[LeetCode] 141 | Linked List Cycle | Python

yun_s 2022. 3. 8. 09:59
728x90
반응형

문제 링크: https://leetcode.com/problems/linked-list-cycle/


문제

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.


조건

  • The number of the nodes in the list is in the range [0, $10^4$].
  • $-10^5$ <= Node.val <= $10^5$
  • pos is -1 or a valid index in the linked-list.

내 풀이

전에 이 문제의 심화과정(Linked List Cycle II)을 했었다.

위 문제에서는 순환 여부 및 순환 시작점까지 찾았다.

하지만 이번 문제는 순환 여부만 판단하면 되므로 좀 더 쉬운 문제다.

전에 풀었던 것처럼 Floyd의 순환찾기 알고리즘을 사용한다.


코드

# 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:
        if not head or not head.next:   return False
        fast, slow = head, head
        
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            if fast == slow:
                return True
            
        return False

 

728x90
반응형
Comments