標(biāo)簽:雙指針
力扣: 141. 環(huán)形鏈表
給定一個鏈表,判斷鏈表中是否有環(huán)。
如果鏈表中有某個節(jié)點(diǎn)专酗,可以通過連續(xù)跟蹤 next 指針再次到達(dá),則鏈表中存在環(huán)盗扇。 為了表示給定鏈表中的環(huán)祷肯,我們使用整數(shù) pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1疗隶,則在該鏈表中沒有環(huán)佑笋。注意:pos 不作為參數(shù)進(jìn)行傳遞,僅僅是為了標(biāo)識鏈表的實(shí)際情況斑鼻。
如果鏈表中存在環(huán)蒋纬,則返回 true 。 否則坚弱,返回 false 蜀备。
import java.util.HashSet;
import java.util.Set;
/**
* @author: 86182
* @description: 141. 環(huán)形鏈表
* 給定一個鏈表,判斷鏈表中是否有環(huán)荒叶。
* @date: 2021/4/6 16:59
*/
class Node {
int val;
Node next;
Node(int x) {
val = x;
next = null;
}
}
public class listHasCycle {
public static void main(String[] args) {
Node node1 = new Node(0);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
Node node = node3;
node3.next = node2;
node2.next = node1;
node1.next = node4;
node4.next = node2;
//boolean flag = func(node);
boolean flag = func2(node);
System.out.println(flag);
}
private static boolean func2(Node head) {
Set<Node> set = new HashSet<>();
while (head != null){
if(!set.add(head)){
return true;
}
head = head.next;
}
return false;
}
private static boolean func(Node head) {
if(head == null || head.next == null){
return false;
}
Node fast = head;
Node slow = head;
while (fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return false;
}
}