141. 环形链表

双指针法

class Solution {
    public boolean hasCycle(ListNode head) {

        /**
         * 判断是否存在环形链表:创建快慢指针,从头节点出发,如果两个指针能相遇,说明存在环形链表
         */
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null){

            fast = fast.next.next;
            slow = slow.next;

            if (fast == slow){
                return true;
            }
        }

        return false;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/linked-list-cycle/

posted @ 2022-02-18 13:29  振袖秋枫问红叶  阅读(22)  评论(0)    收藏  举报