LeetCode——237. Delete the node (non-recursive) speed pointer in the linked list

Address: https://leetcode.cn/problems/linked-list-cycle/
insert image description here
The idea of ​​solving this question is mainly to use fast and slow pointers, the fast pointer takes two steps at a time, and the slow pointer takes two steps at a time.

public class 环形链表_非递归 {
    
    
    class ListNode {
    
    
        int val;
        ListNode next;
        ListNode(int x) {
    
    
            val = x;
            next = null;
        }
        public boolean hasCycle(ListNode head) {
    
    
            if (head ==null || head.next==null) return false;
            ListNode slow = head;
            ListNode fast = head.next;
            //进行循环
            while (fast !=null && fast.next !=null){
    
    
                //如果快慢指针重合 那么结束循环,重合就代表有环
                if (slow == fast) return true;
                slow = slow.next;
                fast = fast.next.next;
            }
            return false;
        }
    }
}

Guess you like

Origin blog.csdn.net/m0_62491934/article/details/128739319
Recommended