1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 // 定义临时变量-快慢两个指针 15 ListNode fast = head; 16 ListNode slow = head; 17 // 循环链表 18 while(fast != null && fast.next != null) { 19 // 快指针走两步 20 fast = fast.next.next; 21 // 慢指针走一步 22 slow = slow.next; 23 // 快慢指针相遇则说明有环 24 if (fast == slow) { 25 return true; 26 } 27 } 28 // 链表遍历到尾节点说明没有环 29 return false; 30 } 31 }
标签:slow,ListNode,fast,next,链表,有环,06,指针 From: https://www.cnblogs.com/StringBuilder/p/17835062.html