"Sword Finger Offer"-55. The entry node of the ring in the linked list

1. Knowledge points of this question

Linked list

2. Title description

For a linked list, if it contains a ring, please find the entry node of the ring of the linked list, otherwise, output null.

3. Problem solving ideas

  1. Traverse each node of the singly linked list
  2. If the current node address does not appear in the Set, it is stored in the Set
  3. If it appears in Set, the current node is the entry node of the ring
  4. After the entire singly linked list is traversed, if it does not appear in the Set, there is no ring

4. Code

public class Solution {
    
    

    public ListNode EntryNodeOfLoop(ListNode pHead) {
    
    
        HashSet<ListNode> set = new HashSet<>();
        // 遍历单链表的每个结点
        while (pHead != null) {
    
    
            if (set.contains(pHead)) {
    
    
                // 出现在 Set 中,则当前结点就是环的入口结点
                return pHead;
            } else {
    
    
                // 如果当前结点地址没有出现在 Set 中,则存入 Set 中
                set.add(pHead);
                pHead = pHead.next;
            }
        }
        // 整个单链表遍历完,若没出现在 Set 中,则不存在环
        return null;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/112993888