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;
}
}
本文介绍了两种方法来检测给定的单向链表中是否存在环:一种是使用快慢指针,当它们相遇时环存在;另一种是利用哈希表记录已访问节点,若遇到重复则为环。
5039

被折叠的 条评论
为什么被折叠?



