1.思路
- 快慢指针法
- 慢指针
跳1,快指针跳2 - 如果
有环,快指针会在环里面转圈圈,所以快慢指针一定会相遇
2.代码
class ListNode {
int val; //自身的值
ListNode next; //下一个节点的地址
ListNode(int x) {
val = x;
next = null;
}//创建一个节点
}
public class Solution {
public boolean hasCycle(ListNode head) {
//快慢指针法
if(head==null){
return false;
}
ListNode slow = head;
ListNode fast = head;
while(slow.next!=null && fast.next!=null && fast.next.next!=null){
slow =slow.next;
fast = fast.next.next;
if(slow==fast){
return true;
}
}
return false;
}
}