/**
* 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;
ListNode quick = head.next;
while(quick!=null&&quick.next!=null){
if(slow==quick){
return true;
}
//后移一位
slow=slow.next;
//后移两位
quick=quick.next.next;
}
return false;
}
}
环形列表(快慢指针法)
最新推荐文章于 2024-05-20 18:12:41 发布