Ring List II
Topic description: Given a linked list, return the first node where the linked list begins to enter the ring. Returns null if the linked list has no cycle.
To represent a cycle in a given linked list, we use the integer pos to denote the position in the linked list where the tail of the linked list is connected (indexes start at 0). If pos is -1, there are no cycles in the list. Note that pos is only used to identify the ring case and is not passed as an argument to the function.
Description: Modification of the given linked list is not allowed.
Advanced:
Can you solve this problem in O(1) space?
For example descriptions, please refer to the official website of LeetCode.
Source: LeetCode
Link: https://leetcode-cn.com/problems/linked-list-cycle-ii/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization, and for non-commercial reprints, please indicate the source.
Solution 1: Hash table
HashSet determines whether the node is repeated.
Solution 2: Double pointer method
Using fast and slow nodes, if there is a cycle, these two nodes must meet.
import java.util.HashSet;
import java.util.Set;
public class LeetCode_142 {
/**
* 哈希
*
* @param head
* @return
*/
public static ListNode detectCycle(ListNode head) {
if (head == null) {
return null;
}
Set<ListNode> nodes = new HashSet<>();
nodes.add(head);
while (head.next != null) {
// 如果next节点在哈希表中出现过,说明成环了, 而且next节点肯定是入环点,直接返回
if (nodes.contains(head.next)) {
return head.next;
}
nodes.add(head.next);
head = head.next;
}
return null;
}
/**
* 双指针法
*
* @param head
* @return
*/
public static ListNode detectCycle2(ListNode head) {
if (head == null) {
return null;
}
ListNode slow = head, fast = head;
while (fast != null) {
slow = slow.next;
if (fast.next != null) {
fast = fast.next.next;
} else {
return null;
}
if (fast == slow) {
ListNode ptr = head;
while (ptr != slow) {
ptr = ptr.next;
slow = slow.next;
}
return ptr;
}
}
return null;
}
public static void main(String[] args) {
ListNode head = new ListNode(3);
head.next = new ListNode(2);
head.next.next = new ListNode(0);
head.next.next.next = new ListNode(-4);
head.next.next.next.next = head.next;
System.out.println(detectCycle(head) == null ? -1 : detectCycle(head).val);
System.out.println(detectCycle2(head) == null ? -1 : detectCycle2(head).val);
}
}
[Daily Message] are too many unpredictable things in the world, but no matter what, the society will still operate. No matter how great a person's achievements are, they are very insignificant in the world, so cherish every minute and every second.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。