题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解答
一般思路:HashSet
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<ListNode>();
while (head != null) {
if (set.contains(head)) return true;
set.add(head);
head = head.next;
}
return false;
}
}
without using extra space:追及问题
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) return false;
ListNode slow = head, fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) return false;
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}