1. 程式人生 > >【LeetCode-面試演算法經典-Java實現】【142-Linked List Cycle II(單鏈表中有環II)】

【LeetCode-面試演算法經典-Java實現】【142-Linked List Cycle II(單鏈表中有環II)】

原題

  Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
  Follow up:
  Can you solve it without using extra space?

題目大意

  給定一個單鏈表,如果它有環,返回環入口的第一個節點,否則返回null

解題思路

  先判斷連結串列是否有環,使用快(fast)慢指標(slow),解法見【141-Linked List Cycle(單鏈表中有環)】,如果沒有環就返回null,如果有環,有fast=slow,就讓讓slow重新指向連結串列頭,然後兩個指標每次同時移動一個位置,直到兩連結串列相遇,相遇點就是環的入口結點。

程式碼實現

結點類

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) { break; } } if (fast == null || fast.next == null) { return null; } slow = head; while (fast != slow) { fast = fast.next; slow = slow.next; } return
slow; } }

評測結果

  點選圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中檢視完整圖片。

這裡寫圖片描述

特別說明