【LeetCode】141. Circular Linked List Advanced Questions 142. Circular Linked List II

 141. Circular Linked List

This question is still done with the classic fast and slow pointer method . Let the fast pointer take two steps each time, and the slow one step. If there is a ring, they will definitely meet at some node inside the ring. Thought has something to do with physics knowledge. If there is a ring, then in the process of relative motion, it can be equivalent to the slow pointer standing still, and every time the fast pointer takes a step, it will definitely meet in the end. This is also the condition for judging that there is a ring.

If there is no loop, the fast pointer will definitely be null at the end when it is moving. This is the condition for judging acyclic.

 algorithm code

public 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;
        
    }
}

operation result

 

142. Circular Linked List II

Compared with the previous question, the previous question only needs to judge whether there is a ring or not. This question also returns the first node of the linked list starting to enter the ring on the basis of the previous question. Returns null if the linked list is acyclic.

The idea is to add a pointer to the head node when it is determined that there is a loop. At this time, let the pointer pointing to the meeting point and the newly added (pointing to the head node) these two pointers continue to use the same " Speed" to go back until "meeting" (pointing to the same node), the node referred to at this time is the first node where the linked list starts to enter the ring.

 algorithm code

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

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

            if(fast == slow) {
                ListNode node = head;  //新加入一个指向头结点的指针
                while(node != slow) {
                    node = node.next;
                    slow = slow.next;
                }
                return node; //返回slow也行
            }
        }

        return null;
        
    }
}

operation result

 

Guess you like

Origin blog.csdn.net/m0_73381672/article/details/132066652