1. ๋ฌธ์ œ : https://leetcode.com/problems/linked-list-cycle-ii/

 

2. ํ’€์ด

Floyd Cycle Detection Algorithm ์‚ฌ์šฉ

 

3. ์ฝ”๋“œ

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {

        ListNode slow, fast;

        if(head == null || head.next == null) return null;

        slow = head;
        fast = head.next;

        while(true){

            if(slow == fast) break;

            if(slow.next == null || fast.next == null || fast.next.next == null) return null;

            slow = slow.next;
            fast = fast.next.next;
        }

        ListNode temp;
        temp = head;
        slow = slow.next;

        while(true){
            if(temp == slow) return slow;
            slow = slow.next;
            temp = temp.next;
        }

    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ