142. 環形鏈表 II

142. 環形鏈表 II

給定一個鏈表,返回鏈表開始入環的第一個節點。 若是鏈表無環,則返回 null。node

爲了表示給定鏈表中的環,咱們使用整數 pos 來表示鏈表尾鏈接到鏈表中的位置(索引從 0 開始)。 若是 pos 是 -1,則在該鏈表中沒有環。spa

說明:不容許修改給定的鏈表。
示例 1:指針

輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部鏈接到第二個節點。
image
示例 2:code

輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個環,其尾部鏈接到第一個節點。
imageblog

示例 3:索引

輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環。
imageleetcode

分析:一、哈希法,使用set判斷,找到重複的節點就爲環的開始節點。 二、雙指針法,快慢節點,找到第一次的重複節點,則從頭節點和重複節點到環開始節點的速度同樣,找到頭節點與重複節點的相遇節點。rem


/**
 * 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 meet=null;
        //快節點
        ListNode fast=head;
        //慢節點
        ListNode slow=head;
        while(fast!=null){
            //同時先走一步
           fast=fast.next;
           slow=slow.next;
           if(fast==null){
               return null;
           }
           //快節點再走一步
            fast=fast.next;
            //相等則找到meet節點,找到直接跳出
            if(fast==slow){
                meet=fast;
                break;
            }
        }
        if(meet==null){
            return null;
        }
        //而後頭節點和相遇節點同時走,找他們相遇節點即環鏈表的開始節點
        while(head!=null&&meet!=null){
            if(head==meet){
                return meet;
            }
            head=head.next;
            meet=meet.next;
        }
        return null;
    }
}
相關文章
相關標籤/搜索