본문 바로가기

자료구조,알고리즘

LeetCode-141 Linked List Cycle 파이썬 풀이

 

Linked List Cycle - LeetCode

Can you solve this real interview question? 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 continuo

leetcode.com

문제

주어진 링크드 리스트가 순환하는지 순환하지 않는지를 판단하는 문제입니다.

풀이

싸이클이 있는 링크드 리스트의 특성을 알고 있으면 쉽게 풀 수 있는데, 이동하는 크기가 다른 두 노드가 있다면

각 노드의 싸이클은 언젠가 겹치게 됩니다. 이 특성을 이용해 두 노드가 같아질 때 True를 그렇지 않으면 False를 반환하면 됩니다. 

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        node1 = head
        node2 = head

        while node1 and node1.next:
            node2 = node2.next
            node1 = node1.next.next

            if node1 == node2:
                return True

        return False