/**
* 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) {
ListNode fast=head;
ListNode slow=head;
if(head==null||head.next==null||head.next.next==null){
return false;
}
fast=head.next;
while(fast!=null&&fast.next!=null&&fast!=slow){
fast=fast.next.next;//快指针一次走两步
slow=slow.next;//慢指针一次走一步
}
if(fast==null||fast.next==null){//没有换fast指针肯定会先走出链表
return false;
}
return true;//有环的话fast指针和slow指针最终一定会在环内相遇
}
}
* 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) {
ListNode fast=head;
ListNode slow=head;
if(head==null||head.next==null||head.next.next==null){
return false;
}
fast=head.next;
while(fast!=null&&fast.next!=null&&fast!=slow){
fast=fast.next.next;//快指针一次走两步
slow=slow.next;//慢指针一次走一步
}
if(fast==null||fast.next==null){//没有换fast指针肯定会先走出链表
return false;
}
return true;//有环的话fast指针和slow指针最终一定会在环内相遇
}
}