题目
解法一 哈希表
- 将遍历过的节点存入哈希表,利用哈希表数据唯一性
/**
* 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) return false;
Set<ListNode> s = new HashSet<>();
while(head != null){
if(!s.add(head)) return true;
head = head.next;
}
return false;
}
}
解法二(最优解) 快慢指针
- 此解法空间复杂度O(1), 时间复杂度O(n)
/**
* 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) return false;
ListNode slowPointer = head;
ListNode fastPointer = head.next;
while(slowPointer != fastPointer){
if(fastPointer == null || fastPointer.next == null) //这里只需判断fastPointer
return false;
slowPointer = slowPointer.next;
fastPointer = fastPointer.next.next;
}
return true;
}
}