Aunt Guan is participating in the “Java Theme month – Java brush question clocking”, see the activity link for more details

First of all, I want to clarify that every algorithm problem has multiple solutions, and we’ll just talk about a few excellent solutions in LeetCode ~, hopefully

Can help you, that we first look at the topic description ~

I. Title Description:

Given a linked list, determine whether there are rings in the list. If there is a node in the list that can be reached again by following the next pointer continuously, then there is a ring in the list. To represent the rings in a given list, we use the integer pos to represent where in the list the tail joins (the index starts at 0). If pos is -1, there are no rings in the linked list. Note: POS is not passed as an argument, just to identify the actual state of the linked list. Returns true if there are rings in the list. Otherwise, return false.

Advanced: Can you solve this problem with O(1) (i.e., constant) memory?

Example 1:Input: head = [3,2,0,-4], pos = 1 output: true explanation: there is a ring in the linked list whose tail is connected to a second node. Example 2:

Input: head = [1,2], pos = 0 output: true explanation: there is a ring in the linked list whose tail is connected to the first node. Example 3:

Input: head = [1], pos = -1 Output: false Explanation: There are no loops in the linked list.

Val <= 105 pos is -1 or a valid index in the linked list.

Ii. Analysis of Ideas:

By iterating through each node in the list, you can determine whether the next node is already iterated

Three, code implementation

public boolean hasCycle(ListNode head) {
        // Here we use set to save the visited nodes, and then take advantage of the non-duplicative nature of set. Checks whether the node has been accessed
        Set<ListNode> seen = new HashSet<ListNode>();
        while(head ! =null) {
            if(! seen.add(head)) {return true;
            }
            head = head.next;
        }
        return false;
    }
Copy the code

Brush question summary

If you have other ideas to solve the problem, as long as you can achieve the requirements, it is no problem, all roads lead to Rome, not just limited to the solution I said ha ~, excellent ideas and code is more learning significance, let’s work together