常规思路:放到哈希表里面,如果碰到相同的,就认为是有环
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
进阶思维:快慢指针
/**
* 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, fast = head.next; // 双指针
while (slow != fast) {
if (fast == null || fast.next == null) {
return false; //快的跑到终点了,没有环
}
slow = slow.next;
fast = fast.next.next;
}
return true; //当slow==fast时,说明快的跑了一圈多碰到了慢的
}
}
142. 环形链表 II
这个也可以用哈希表来实现;另外一种方式..