Given a linked list, determine if it has a cycle in it.
Follow up:Can you solve it without using extra space?
Subscribe to see which companies asked this question.
題目
給定一個鏈表,判斷它是否有環。
Approach #1 (Two Pointers)
使用兩個指針slow,fast。兩個指針都從表頭開始走,slow每次走一步,fast每次走兩步,如果fast遇到null,則說明沒有環,返回false;如果slow==fast,說明有環,并且此時fast超了slow一圈,返回true。
為什么有環的情況下二者一定會相遇呢?因為fast先進入環,在slow進入之后,如果把slow看作在前面,fast在后面每次循環都向slow靠近1,所以一定會相遇,而不會出現fast直接跳過slow的情況。
代碼
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
// write your code here
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head;
while (true) {
if (fast == null || fast.next == null) {
return false; //遇到null了,說明不存在環
}
slow = slow.next;
fast = fast.next.next;
if (fast == slow) {
return true; //第一次相遇在Z點
}
}
}
}
Approach #2 (Hash Table)
想法很簡單,如果鏈表中有一個環,那么我們只需要檢查是否有一個節點被重復訪問過,這個自然可以想到使用哈希表。
我們依次訪問所有的鏈表節點,并將其節點的引用放到哈希表中,如果當前節點為空,就說明,我們已經到達了鏈表的末尾,而且這時候鏈表沒有環,如果當前訪問的節點在哈希表中出現過,也就是說明鏈表中有一個環。
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null)
return false;
Set<ListNode> nodeSeen = new HashSet<ListNode>();
while(head != null) {
if(!nodeSeen.contains(head))
nodeSeen.add(head);
else
return true;
head = head.next;
}
return false;
}