Double pointer method circular linked list II

topic

LeetCode 142. Circular Linked List II

Given a linked list, return the first node where the linked list starts to enter the loop. If the linked list has no rings, null is returned.

In order to represent the rings in a given linked list, we use the integer pos to indicate the position where the end of the linked list is connected to the linked list (the index starts from 0). If pos is -1, then there is no ring in the linked list. Note that pos is only used to identify the ring, and will not be passed to the function as a parameter.

Note: It is not allowed to modify the given linked list.

Advanced:

Can you solve this problem using O(1) space?

Example 1:

Insert picture description here

Input: head = [3,2,0,-4], pos = 1
Output: Return the linked list node with index 1
Explanation: There is a ring in the linked list, and its tail is connected to the second node.
Example 2:

Insert picture description here

Input: head = [1,2], pos = 0
Output: Return the linked list node with index 0.
Explanation: There is a ring in the linked list whose tail is connected to the first node.
Example 3:
Insert picture description here

Input: head = [1], pos = -1
Output: return null
Explanation: There is no ring in the linked list.

prompt:

The range of the number of nodes in the linked list is in the range [0, 104]
-105 <= Node.val <= 105
The value of pos is -1 or a valid index in the linked list

Problem-solving ideas and algorithms

Insert picture description here

Code

public class Solution {
    
    
    public ListNode detectCycle(ListNode head) {
    
    
        ListNode pos = head;
        Set<ListNode> visited = new HashSet<ListNode>();
        while (pos != null) {
    
    
            if (visited.contains(pos)) {
    
    
                return pos;
            } else {
    
    
                visited.add(pos);
            }
            pos = pos.next;
        }
        return null;
    }
}

Insert picture description here

Code

public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        ListNode slow = head, fast = head;
        while (fast.next!=null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (fast == slow) {
                ListNode ptr = head;
                while (ptr != slow) {
                    ptr = ptr.next;
                    slow = slow.next;
                }
                return ptr;
            }
        }
        return null;
    }
}

Guess you like

Origin blog.csdn.net/a12355556/article/details/113445689