LeetCode—linked-list-cycle(检测是否有环)—Java

题目描述

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

思路解析

这个只需要快慢指针的方法就可以检测是否有环。

代码

/**
 * 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||head.next.next==null){
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next.next;
        while(slow!=fast){
            if(fast.next!=null&&fast.next.next!=null){
                fast = fast.next.next;
                slow=slow.next;
            }
            else{
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/lynn_baby/article/details/80386556