思路
1.哈希法
按链表顺序遍历,每次经过一个节点就标记当前节点是否存在,如果存在就表示有环(并非第一次到达),如果不在就将其标记为访问过,等待下一次回环的判断
2:快慢指针(很帅好吧)
Accode:
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) {
HashMap<ListNode, Integer> map = new HashMap<>();
while (head!=null){
if (map.containsKey(head))return true;
map.put(head,1);
head= head.next;
}
return false;
}
}
2:
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;
}
}
over~