环形链表



题解:双指针
一个指针一次移动2步,一个指针一次移动一步。如果两个指针相遇证明存在环.

/**
 * 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) return false;
        ListNode l=head,r=head;
        while(true){
            l=l.next;
            r=r.next==null? null:r.next.next;
            if(l==r&&l!=null){
                return true;
            }
            if(r==null){
                return false;
            }
        }
       
    }
}


不一样的烟火
原文地址:https://www.cnblogs.com/cstdio1/p/13334498.html