1. 程式人生 > 其它 >Leecode no.142 環形連結串列 II

Leecode no.142 環形連結串列 II

package leecode;

import java.util.HashSet;
import java.util.Set;

/**
* 142. 環形連結串列 II
*
* 給定一個連結串列,返回連結串列開始入環的第一個節點。如果連結串列無環,則返回null。
*
* 如果連結串列中有某個節點,可以通過連續跟蹤 next 指標再次到達,則連結串列中存在環。 為了表示給定連結串列中的環,評測系統內部使用整數 pos 來表示連結串列尾連線到連結串列中的位置(索引從 0 開始)。如果 pos 是 -1,則在該連結串列中沒有環。注意:pos 不作為引數進行傳遞,僅僅是為了標識連結串列的實際情況。
*
* 不允許修改 連結串列。
*
* @author Tang
* @date 2021/12/15
*/
public class DetectCycle {

/**
* 玩不起了 直接用散列表判斷是否存在環
*
* @param head
* @return
*/
public ListNode detectCycle(ListNode head) {
Set set = new HashSet();

while(head != null) {
if(set.contains(head)) {
return head;
}
set.add(head);
head = head.next;
}
return null;
}

/**
* 雙指標判斷是否存在環
*
* @param head
* @return
*/
public Boolean detectCycle2(ListNode head) {

ListNode fast = head;
ListNode slow = head;

while(fast != null && fast.next != null) {
//快指標走兩步
fast = fast.next.next;
//慢指標走一步
slow = slow.next;
if(slow == fast) {
return true;
}
}
return false;

}

public static void main(String[] args) {

}



}