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;
}
}
}
'๐ป Coding Problems Solving > Two Pointers | Binary Search| LinkedList' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] Add Two Numbers (0) | 2023.07.13 |
---|---|
[LeetCode] Remove Duplicates from Sorted List II (0) | 2023.07.12 |
[ํ๋ก๊ทธ๋๋จธ์ค] ์ฐ์๋ ๋ถ๋ถ ์์ด์ ํฉ (์๋ฐ java) (0) | 2023.05.15 |
[LeetCode] 3Sum (0) | 2023.04.12 |
[BOJ 1806] ๋ถ๋ถํฉ (java) (0) | 2023.04.05 |
์ต๊ทผ๋๊ธ