22.环形链表II
方法一:快慢指针
/**
* 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) {
if(head == null || head.next == null){
return null;
}
ListNode slow = head,fast = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(slow == fast) break;
}
if(slow != fast){
return null;
}
ListNode ptr = head;
while(slow != ptr){
ptr = ptr.next;
slow = slow.next;
}
return slow;
}
}
方法二:哈希表
/**
* 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) {
ListNode pos = head;
Set<ListNode> visited = new HashSet<>();
while(pos != null){
if(visited.contains(pos)){
return pos;
}
visited.add(pos);
pos = pos.next;
}
return null;
}
}