直接全部拆解链表,每次向下遍历时,将当前指针的next都指向head,若有环,最终下一个会跳到head处,此时与head相等则有环!!!若无环,则最终下一个指针会指向null;
/**
* 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) {
ListNode p = head;
ListNode q;
while (p != null) {
q = p.next;
if (q== head)
return true;
p.next = head;
p = q;
}
return false;
}
}
京公网安备 11010502036488号