-
[LeetCode] Linked List Cycle알고리즘 2020. 8. 23. 17:44
문제
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list.
Approach
두 개의 포인터를 선언하고
하나는 두 칸씩, 하나는 한 칸씩 이동하도록 한다.
포인터가 NULL 이되면 싸이클이 없는 것이고
싸이클이 있다면 두 포인터가 같게 되는 순간이 온다.
Code
https://github.com/chi3236/algorithm/blob/master/LeetCode_Linked_List_Cycle.cpp
'알고리즘' 카테고리의 다른 글
[백준] MooTube (0) 2021.08.10 [LeetCode] Jump Game2 (0) 2020.08.30 [LeetCode] Combination Sum (0) 2020.05.04 [LeetCode] Word Break II (0) 2019.12.19 [LeetCode] Word Break (0) 2019.12.19