Ring list 00

topic link

circular linked list

topic description


important point

  • none

Solution ideas

  • The fast and slow pointers judge whether there is a ring in the linked list. If there is no ring in the linked list, the fast and slow pointers will never meet. position, which the slow pointer reaches for the first time)

the code

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    
    
    public boolean hasCycle(ListNode head) {
    
    
        ListNode quick = head;
        ListNode slow = head;
        while (quick != null && quick.next != null) {
    
    
            quick = quick.next.next;
            slow = slow.next;
            if (quick == slow) {
    
    
                return true;
            }
        }
        return false;
    }
}

key point

  • The idea of ​​fast and slow pointer

Guess you like

Origin blog.csdn.net/weixin_51628158/article/details/131600287