(链表)06-判断链表中是否有环

 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 }

 

posted @ 2023-11-15 22:49  StringBuilder  阅读(3)  评论(0编辑  收藏  举报