判断单链表是否有环
代码实现
package 剑指offer;
import java.util.HashSet;
import java.util.List;
/**
* @author WangXiaoeZhe
* @Date: Created in 2019/11/22 16:55
* @description:
*/
public class Main13 {
public static void main(String[] args) {
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
/**
* 利用set的性质
* @param head
* @return
*/
public boolean hasCycle(ListNode head){
/**
* 创建集合对象
*/
HashSet<ListNode> set = new HashSet<>();
/**
* 遍历链表
*/
ListNode p=head;
while(p!=null){
if (set.contains(p)) {
return true;
} else {
set.add(p);
}
p=p.next;
}
return false;
}
/**
* 快慢指针遍历法
*/
public boolean hasCycle2(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast=head;
ListNode slow=head;
while (fast != null && fast.next != null) {
slow=slow.next;
fast=fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}