问:对于一个给定的链表,返回环的入口节点,如果没有环,返回null。
解:时间复杂度O(n),空间复杂度O(n)。
import java.util.Set;
import java.util.HashSet;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
Set set = new HashSet<ListNode>();
while (!set.contains(head) && head != null) {
set.add(head);
head = head.next;
}
return head;
}
}
问:对于一个给定的链表,返回环的入口节点,如果没有环,返回null。要求:空间复杂度O(1)。
解:时间复杂度O(n),空间复杂度O(1)。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int