题目
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
这个pos没什么用
思路
一: 用set存 如果存到重复值 说明有环
时间复杂度:O(n)
空间复杂度 O(n)
二: 快慢指针 如果有环 快慢指针总会相遇
时间复杂度 O(n)
空间复杂度 O(1)
代码
public class Solution {
Set<ListNode> set = new HashSet<>();
public boolean hasCycle(ListNode head) {
while(head != null){
if(set.contains(head))
return true;
else
set.add(head);
head = head.next;
}
return false;
}
}
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null)
return false;
ListNode slow = head;
ListNode fast = head.next;
while(slow!= fast){
//只用判断fast就可
if(fast== null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}