判断给定的链表中是否有环
扩展:
你能给出不利用额外空间的解法么?
/**
* 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) {
//快慢指针找中点slow
ListNode slow =head;
ListNode fast=head;
while(fast!=null&&fast.next!=null) {
slow = slow.next;
fast = fast.next.next;
//快慢指针重合必有环
if (slow == fast)
return true;
}
//若是空链表或者是只有一个元素,一定不是环
if(fast==null ||fast.next==null){
return false;
}
//???????加上以后效率变快?????????
if (slow == fast)
return true;
return false;
}
}