LeetCode_141. 环形链表

如果是环,两个速度不一样的数一定会在循环中相遇
public class S_141 {
    public class Solution {
        public boolean hasCycle(ListNode head) {
            // 判断是否是空的
            if(head == null||head.next == null){
                return false;
            }
            // 建立两个步进速度不同的变量
            ListNode fast = head;
            ListNode slow = head;
            // 在保证当前和下一个都有值的时候
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next.next;
                // 快的和慢的相遇代表是一个环
                if(slow == fast){
                    return true;
                }
            }
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/king1994wzl/article/details/82848665