题目来源:LeetCode
给定一个链表,判断链表中是否有环。
下面分别给出空间复杂度O(n)的解法和O(1)的解法。
解法1:利用Hash表
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow, fast;
slow = fast = head;
// 有环的时候,会一直在while循环里,出了while循环则表明没有环
while(fast!=null){
fast = fast.next;
if(fast==null) return false;
fast = fast.next;
if(fast==null) return false;
if(fast == slow) return true;
slow = slow.next;
}
return false;
}
解法2:快慢指针
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow=head;
ListNode fast = head.next;
while(slow!=fast){
if(fast==null || fast.next==null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
下面的写法不同,但上面的更优雅
public boolean hasCycle(ListNode head) {
if(head==null || head.next==null) return false;
ListNode slow, fast;
slow = fast = head;
// 有环的时候,会一直在while循环里,出了while循环则表明没有环
while(fast!=null){
fast = fast.next;
if(fast==null) return false;
fast = fast.next;
if(fast==null) return false;
if(fast == slow) return true;
slow = slow.next;
}
return false;
}