LeetCode 141/142. Linked List Cycle (环形链表的两道题)

一、判断是否是环形链表
without using extra space

public boolean hasCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            
            if(fast == slow) {
                return true;
            } 
        }
        return false;
    }

或者:

public boolean hasCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(true) {
            if(fast == null || fast.next == null) return false;
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                return true;
            } 
        }
    }

二、找环形链表的入口结点
Given a linked list, return the node where the cycle begins
If there is no cycle, return null.
without using extra space

public ListNode detectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(true) {
            if(fast == null || fast.next == null) return null;
            fast = fast.next.next;
            slow = slow.next;
            //第一次相遇
            if(slow == fast) {
                break;
            }
        }

        //“准备”第二次相遇
        fast = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

图解:

以下图片来自题解出的精选答案:
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第1张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第2张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第3张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第4张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第5张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第6张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第7张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第8张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第9张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第10张图片
LeetCode 141/142. Linked List Cycle (环形链表的两道题)_第11张图片

你可能感兴趣的:(#,LeetCode链表,LeetCode分类刷题)