判断链表中是否有环
描述
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
输入分为2部分,第一部分为链表,第二部分代表是否有环,然后回组成head头结点传入到函数里面。-1代表无环,其他的数字代表有环,这些参数解释仅仅是为了方便读者自测调试
解题
单链表
public class ListNode {
int val;
ListNode next;
ListNode(int x){
val = x;
next = null;
}
}
Solution1
/**
* 单链表是否有环
* 快慢指针法
*/
public class Solution {
public boolean hasCycle(ListNode head){
if(head == null) return false;
ListNode slow=head;
ListNode fast=head;
while (fast!=null&&fast.next!=null){
slow=slow.next;//步长为1
fast=fast.next.next;//步长为2
if(slow==fast){
return true;
}
}
return false;
}
}
Solution2
/**
* 单链表是否有环
* 集合方法
*/
import java.util.HashSet;
import java.util.Set;
public class Solution2 {
public boolean hasCycle(ListNode head){
Set<ListNode> set = new HashSet<>();
while (head!=null){
if (set.contains(head)) return true;
set.add(head);
head=head.next;
}
return false;
}
}
Solution3
/**
* 单链表是否有环
* 拆分节点方法
*/
public class Solution3 {
public boolean hasCycle(ListNode head){
if (head==null||head.next==null) return false;
if (head.next==head) return true;
ListNode nexnode=head.next;
head.next=head;//节点拆分
return hasCycle(nexnode);
}
}