给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置
(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
如果链表中存在环,则返回 true 。 否则,返回 false 。
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。
头部处理:没有节点或只有一个结点,都不可构成环形链表
只有两个结点可以构成
分析:遍历如果遇到null,则一定不是环形
遍历如果遇到重复的node,则一定是环形
1.解题思路一:双指针:slow=slow.fast;fast=fast.next.next;
条件:slow!=fast,是环形,fast,slow相遇,return true;
fast跑两圈,slow跑一圈
非环形,fast一定先遇到null空节点,return false; Time:O(N) Space:0
/**
* 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;
}
ListNode slow=head;
ListNode fast=head.next;
while(slow!=fast){
if(fast==null||fast.next==null){
return false;
}
slow=slow.next;
fast=fast.next.next;
}
return true;
}
}
2.解题思路二:HashSet存ListNode: cur=cur.next遍历:cur=null一定不是环形
cur!=null,此node在hashset中有,是环形
没有此node,放入set中
Time:O(N) Space:O(N)
代码:
/**
* 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<ListNode> set=new HashSet<>();
ListNode cur=head;
while(cur!=null){
if(set.contains(cur)){
return true;//包含结点
}else{
set.add(cur);//不包含则添加
}
cur=cur.next;
}
//遇到空节点跳出while循环,return false;
return false;
}
}