1. 程式人生 > 其它 >Mobirise for Mac(手機網站建設軟體) v5.4.1正式版

Mobirise for Mac(手機網站建設軟體) v5.4.1正式版

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

To represent a cycle in the given linked list, we use an integerposwhich represents the position (0-indexed)in the linked list where tail connects to. Ifposis-1, then there is no cycle in the linked list.

Note:Do not modify the linked list.

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: tail connects to node index 1
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:

Input: head = [1,2], pos = 0
Output: tail connects to node index 0
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:

Input: head = [1], pos = -1
Output: no cycle
Explanation: There is no cycle in the linked list.

Follow-up:

Can you solve it without using extra space?

單鏈表中的環二。題意是給一個連結串列,如果這個連結串列中有環,請return環的起點;若沒有,return null。

時間O(n)

空間O(1)

思路;

快慢指標:如相遇則有環,第一次相遇後,快指標回到頭節點,開始分別都以一步的方式往前走,第二次相遇則是入環節點

因為快慢指標的速度是一個2步一個1步,所以當兩個指標相遇的時候,fast走過的長度一定是slow的兩倍。兩者相遇的地方一定是環的起點。

public class Solution {
    public ListNode detectCycle(ListNode head) {
       if(head==null || head.next==null || head.next.next==null){
           return null;
       }
        ListNode s=head.next;
        ListNode f=head.next.next;
        while(s!=f){
            if(f.next==null||f.next.next==null){
                return null;
            }
             f=f.next.next;
            s=s.next;
           
        }
        //f回到頭節點,s停,f,s一步一步往前走,相遇了則是入環節點
        f=head;
        while(s!=f){
             s=s.next;
            f=f.next;
           
        }
        return s;

    }
}