單鏈表中有環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?node

題目大意

  給定一個單鏈表,若是它有環,返回環入口的第一個節點,不然返回null算法

解題思路

  先判斷鏈表是否有環,使用快(fast)慢指針(slow),解法見單鏈表中有環,若是沒有環就返回null,若是有環,有fast=slow,就讓讓slow從新指向鏈表頭,而後兩個指針每次同時移動一個位置,直到兩鏈表相遇,相遇點就是環的入口結點。spa

代碼實現

結點類.net

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;
    }
}
相關文章
相關標籤/搜索