给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
提示:
- 链表中节点的数目范围是 [0, 104]
- -105 <= Node.val <= 105
- pos 为 -1 或者链表中的一个 有效索引 。
解法一
常规做法,解法二为进阶做法,满足空间复杂度的要求。
/**
* 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) {
//特判
if (head == null || head.next == null) return false;
//set
//存储每个节点,当有重复时说明有环
Set<ListNode> set = new HashSet<>();
//遍历链表
ListNode temp = head;
while(temp != null) {
//如果添加失败,返回true
if(!set.add(temp)) {
return true;
}
temp = temp.next;
}
//遍历完成,说明没环,返回false
return false;
}
}
解法二
public class Solution {
public boolean hasCycle(ListNode head) {
//特判
if (head == null || head.next == null) return false;
//快慢指针
ListNode fast = head.next;
ListNode slow = head;
while (fast != null && fast.next != null) {
//相遇,返回true
if (fast == slow) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
//跳出循环说明没有环
return false;
}
}