LeetCode 141. Linked List Cycle [Easy]

LeetCode 141.

题目来源:https://leetcode.com/problems/linked-list-cycle

题目难度:Easy

1
2
3
4
5
6
7
8
9
10
11
12
13
// 链表的结构

/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/

解法1[Java]:快慢指针

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;
}
}

解法2[Java]:Hash表

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;
}