leetcode-141-linked-list-cycle

Description

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1:

1
2
3
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

img

Example 2:

1
2
3
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

img

Example 3:

1
2
3
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

img

思路0

給一個足夠大的數,如果還沒走出鏈錶很大概率有環。

1
2
3
4
5
6
7
8
9
10
11
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
while(head.next != null && head.next.val != Integer.MIN_VALUE){
head.val = Integer.MIN_VALUE; // 将已遍历的元素作标记
head = head.next;
}
if(head.next == null) return false;
return true;
}
}

####思路1

題意可知這是判斷鏈錶是否是環形鏈表,那麼可以使用雙指針,通過使用通過使用具有不同速度的快、慢兩個指針遍歷鏈表,空間復雜度可以被降低至 O(1)O(1)。慢指針每次移動一步,而快指針每次移動兩步。如果列表中不存在環,最終快指針將會最先到達尾部,此時我們可以返回 false。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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) {
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;
}
}

思路2

我們可以通過檢查壹個結點此前是否被訪問過來判斷鏈表是否為環形鏈表。常用的方法是使用哈希表。我們遍歷所有結點並在哈希表中存儲每個結點的引用(或內存地址)。如果當前結點為空結點 null(即已檢測到鏈表尾部的下壹個結點),那麽我們已經遍歷完整個鏈表,並且該鏈表不是環形鏈表。如果當前結點的引用已經存在於哈希表中,那麽返回 true(即該鏈表為環形鏈表)。

1
2
3
4
5
6
7
8
9
10
11
12
public boolean hasCycle(ListNode head) {
Set<ListNode> nodesSeen = new HashSet<>();
while (head != null) {
if (nodesSeen.contains(head)) {
return true;
} else {
nodesSeen.add(head);
}
head = head.next;
}
return false;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×