/**
* 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;
}
ListNode slow = head,fast = head.next; //如果有环,则必会相遇。
while(fast != null && fast.next != null){ //fast==null时,意味着已经遍历到链表的尾节点,快慢指针未相遇,无环
slow = slow.next;
fast = fast.next.next;
if(fast == slow) return true;
}
return false;
}
}
环形链表(判断一个链表是否有环)(Java实现)
最新推荐文章于 2021-10-29 22:04:19 发布