Daily Leetcode - 141. Linked List Cycle

Easy LinkedList 環形

2023 Dec LC challenge

題目 141. Linked List Cycle

  • 確認有環
  • 找入口

確認有環

使用快慢指標,一個快指標、一個慢指標,就想像成跑步相對速度一個跑得快,一個跑得慢,總會相遇。

找到入口

帶把隨想錄

My Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 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 fast = head;
        ListNode slow = head;
        
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                ListNode index1 = fast;
                ListNode index2 = head;
                while(index1 != index2) {
                    index1 = index1.next;
                    index2 = index2.next;
                }
                return index1;
            }
        }
        return null;
    }
}

說明

Licensed under CC BY-NC-SA 4.0
comments powered by Disqus