環形鏈表-leetcode
題目描述
給你一個鏈表的頭節點 head ,判斷鏈表中是否有環。
如果鏈表中有某個節點,可以通過連續跟蹤 next 指針再次到達,則鏈表中存在環。 為了表示給定鏈表中的環,評測系統內部使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。注意:pos 不作為參數進行傳遞 。僅僅是為了標識鏈表的實際情況。
如果鏈表中存在環 ,則返回 true 。 否則,返回 false 。
示例 1:

輸入:head = [3,2,0,-4], pos = 1
輸出:true
解釋:鏈表中有一個環,其尾部連接到第二個節點。
示例 2:

輸入:head = [1,2], pos = 0
輸出:true
解釋:鏈表中有一個環,其尾部連接到第一個節點。
示例 3:

輸入:head = [1], pos = -1
輸出:false
解釋:鏈表中沒有環。
提示:
- 鏈表中節點的數目范圍是
[0, 104] -105 <= Node.val <= 105pos為-1或者鏈表中的一個 有效索引 。
進階:你能用 O(1)(即,常量)內存解決此問題嗎?
解法一
思路:
采用快慢指針,若是有環,最后快慢指針一定會移動到相同的節點上。
/**
* 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) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}
解法二
思路:
來自官方解答。
使用哈希表來存儲所有已經訪問過的節點。每次我們到達一個節點,如果該節點已經存在于哈希表中,則說明該鏈表是環形鏈表,否則就將該節點加入哈希表中。重復這一過程,直到我們遍歷完整個鏈表即可。
代碼:
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while (head != null) {
if (!seen.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}

浙公網安備 33010602011771號