对于快慢指针 可以用来检测链表是否存在环的情况;
https://leetcode-cn.com/problems/linked-list-cycle/
其核心点在于 通过 慢指针是否能等于快指针 的判断 来检测 当前链表是否存在环;
/** * 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) { if(head == null || head.next == null){ return false; } // 使用快慢指针 // 将head作为慢指针 ListNode slow = head; // 将head.next作为快指针 ListNode fast = head.next; // 当快指针不等于慢指针情况下,继续遍历 while (slow != fast) { // 直到快指针为空或快指针的下一个节点为空的情况下表示遍历结束 if (fast == null || fast.next == null) { return false; } // 迭代慢指针 slow = slow.next; // 迭代快指针 fast = fast.next.next; } // 当执行到当前位置表示慢指针遇到了快指针 return true; } }
原文:https://www.cnblogs.com/xingguoblog/p/14189321.html