当前位置:网站首页>leetcode-141. Circular linked list

leetcode-141. Circular linked list

2022-06-11 16:11:00 LuZhouShiLi

subject -141. Circular list

Give you a list of the head node head , Judge whether there are links in the list .

If there is a node in the linked list , It can be done by continuously tracking next The pointer reaches again , Then there is a ring in the linked list . To represent a ring in a given list , The evaluation system uses an integer pos To indicate where the end of the list is connected to the list ( Index from 0 Start ). Be careful :pos Not passed as an argument . Just to identify the actual situation of the linked list .

If there are rings in the list , Then return to true . otherwise , return false .

https://leetcode.cn/problems/linked-list-cycle/

Ideas

  Set speed pointer , Set the initial pointer slow = fast = head, then slow = slow.next, fast = fast.next.next;
That is to say, slow down the pointer by one step , Let's go two steps , If the fast pointer catches up with the slow pointer , The linked list is a circular linked list .

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 left = head;
        ListNode right = head;
        while(right != null && right.next != null)
        {
    
            left = left.next;
            right = right.next.next;
            if(left == right)
            {
    
                return true;
            }
        }
        //  If the cycle conditions are not met   Come out   It means there must be no ring 
        return false;
    }
}
原网站

版权声明
本文为[LuZhouShiLi]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111600162653.html