0%

LeetCode 141. Linked List Cycle

题目:

LeetCode 141. Linked List Cycle

思路:

  1. 最先想到的是遍历链表, 并将结点的内存地址存在HashSet中.如果当前结点的内存地址已经存在,则表示存在环,直接返回true
  2. 还可以用双指针(快慢指针)来解决, 如果两个指针相遇(套圈), 则代表存在环.

    代码实现:

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
/**
* 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;
}
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)){
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}
}