[LeetCode]Linked List Cycle

2023. 5. 2. 20:55·SW개발/코딩테스트

https://leetcode.com/problems/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

 

문제 분석

주어진 링크드 리스트에 사이클이 존재하는지 여부를 구하는 문제입니다.

 

처음 시도한 답안

# 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:
        # Set flag_val for past node.
        # [-10^5 <= Node.val <= 10^5] -> flag_val == 10^6
        flag_val = 10000000

        while head:
            # alreday traversal.
            if head.val == flag_val:
                return True
            
            head.val = flag_val
            head = head.next

        return False

접근 방법

  1. 링크드 리스트를 끝날때까지 순회합니다.
  2. 지나간 노드에 대해서는 flag_val을 설정합니다.
  3. 반복이 끝날때까지 flag_val을 만나지 못했다면 싸이클이 없고, 만났다면 싸이클이 존재합니다.

가장 단순하게 링크드 리스트를 순회하면서 이전에 만난 노드가 있다면 싸이클이 존재하고, 없다면 싸이클이 존재하지 않는 방식으로 해결했습니다.

 

또한, 이 문제는 Hash Table 에 방문한 노드가 있는지 체크하는 방식과 fast(2칸씩 이동), slow(1칸씩 이동)를 활용한 투 포인터 방식으로도 해결할 수 있습니다.

 

 

728x90

'SW개발 > 코딩테스트' 카테고리의 다른 글

[LeetCode]Search in Rotated Sorted Array  (0) 2023.05.04
[LeetCode]Next Permutation  (0) 2023.05.03
[LeetCode]Single Number  (0) 2023.05.01
[LeetCode]Best Time to Buy and Sell Stock  (0) 2023.04.30
[LeetCode]Swap Nodes in Pairs  (0) 2023.04.13
'SW개발/코딩테스트' 카테고리의 다른 글
  • [LeetCode]Search in Rotated Sorted Array
  • [LeetCode]Next Permutation
  • [LeetCode]Single Number
  • [LeetCode]Best Time to Buy and Sell Stock
Leffe_pt
Leffe_pt
개발자로서 성장하면서 배워온 지식과 경험을 공유하는 공간입니다.
  • Leffe_pt
    Leffe's tistory
    Leffe_pt
  • 전체
    오늘
    어제
    • 분류 전체보기 (307)
      • SW개발 (303)
        • 코딩테스트 (172)
        • 개발이야기 (23)
        • IT 용어 (17)
        • Python (22)
        • Django (46)
        • Flask (2)
        • Database (1)
        • SQLAlchemy (0)
        • Javascript (5)
        • Linux, Unix (3)
        • JAVA (2)
        • Spring (10)
      • 회고 (4)
      • 사진 (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    g
    Contributor
    배공파용
    배달비 공유
    django
    오픈소스
    컨트리뷰터
    트리 #AVL #알고리즘 #자료구조
    어플리케이션
    플레이스토어
    배달
    라이프 스타일
    음식
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Leffe_pt
[LeetCode]Linked List Cycle
상단으로

티스토리툴바