給定一個(gè)鏈表,判斷鏈表中是否有環(huán)。
為了表示給定鏈表中的環(huán)贤斜,我們使用整數(shù) pos 來(lái)表示鏈表尾連接到鏈表中的位置(索引從 0 開始)瘩绒。 如果 pos 是 -1,則在該鏈表中沒(méi)有環(huán)堕战。
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個(gè)環(huán)祠饺,其尾部連接到第二個(gè)節(jié)點(diǎn)。
示例 2:
輸入:head = [1,2], pos = 0
輸出:true
解釋:鏈表中有一個(gè)環(huán)勺鸦,其尾部連接到第一個(gè)節(jié)點(diǎn)刽射。
示例 3:
輸入:head = [1], pos = -1
輸出:false
解釋:鏈表中沒(méi)有環(huán)懈息。
題目鏈接:https://leetcode-cn.com/problems/linked-list-cycle/
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
//如果節(jié)點(diǎn)被訪問(wèn)過(guò)怒见,將鏈表內(nèi),對(duì)應(yīng)位置標(biāo)記為true
Map<ListNode,Boolean> flags = new HashMap<>();
while(head != null){
if(flags.get(head) != null){
return true;
}else{
flags.put(head,true);
head = head.next;
}
}
return false;
}
}