环形链表



题解:双指针
一个指针一次移动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;
            }
        }
       
    }
}


posted @ 2020-07-18 08:51  浅滩浅  阅读(107)  评论(0编辑  收藏  举报