题目描述:
判断给定的链表中是否有环。如果有环则返回true,否则返回false。
思想描述:
使用快慢指针(从同一节点出发,快指针始终是慢指针的两倍),若相遇则有环;否则无环。
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, fast =head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if (fast == slow){
return true;
}
}
return false;
}
}