LeetCode: Linked List Cycle 2

이원희·2020년 12월 1일
0

📝 PS

목록 보기
15/65
post-thumbnail

이번 문제는 이전 문제와 비슷한 맥락의 문제이다.
이전 문제는 LinkedList의 순회를 찾는 문제였다면 이번에는 순회되는 지점을 찾는 문제였다.

문제풀이

이전 문제와 동일하게 LinkedList가 순회하는지 확인했다.
이전에는 fast와 slow가 만나면 true를 return 했지만 이번에는 순회가 있다면 while문을 빠져나왔다.

slow를 head로 다시 지정한 뒤에 slow와 fast를 순차탐색하며 둘이 만나는 지점을 찾았다.

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        
        ListNode slow = head;
        ListNode fast = head;
        
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            
            if(slow == fast) {
                break;
            }
        }
        
        if(fast == null || fast.next == null) {
            return null;
        }
        
        slow = head;
        while(slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        
        return slow;
    }
}

0개의 댓글