给定一个链表,判断链表中是否有环。
题解:
前后指针,前指针每次前进2步,后指针每次前进1步,如果有环则一定碰撞
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null){
return false;
}
ListNode pre = head;
ListNode cur = head.next;
while(cur!=null && cur.next!=null){
if(pre==cur){
return true;
}
cur = cur.next.next;
pre = pre.next;
}
return false;
}
}