對於一個給定的鏈表,返回環的入口節點,如果沒有環,返回null

思路:遍歷鏈表,將節點存入Set,遇到重複節點即返回。

import java.util.*;
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null){
            return null;
        }
        Set set = new HashSet();
        set.add(head);
        while(head.next!=null){
            if(set.contains(head.next)){
                return head.next;
            }else{
                set.add(head.next);
                head=head.next;
            }
        }
        return null;
    }
}

補充:不用額外空間的解法


/**
 * 題目描述: 鏈表的入環節點,如果無環,返回null
 * Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
 * Follow up: Can you solve it without using extra space?
 * 思路:
 * 1)首先判斷是否有環,有環時,返回相遇的節點,無環,返回null
 * 2)有環的情況下, 求鏈表的入環節點
 *   fast再次從頭出發,每次走一步,
 *   slow從相遇點出發,每次走一步,
 *   再次相遇即爲環入口點。
 * 注:此方法在牛客BAT算法課鏈表的部分有講解。
 */
//nowcoder pass
public class Solution {
     
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
         
        ListNode meetNode = meetingNode(head);
        if (meetNode == null) {//說明無環
            return null;
        }
         
        ListNode fast = head;
        ListNode slow = meetNode;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
         
        return slow;
    }
     
    //尋找相遇節點,如果無環,返回null
    public ListNode meetingNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return slow;
            }
        }
        return null;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章