环形链表 II
题目描述:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
说明:不允许修改给定的链表。
进阶:
你是否可以使用 O(1) 空间解决此题?
示例说明请见LeetCode官网。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法一:哈希表
HashSet判断节点是否重复。
解法二:双指针法
使用快慢节点,如果有环,则这两个节点必回相遇。
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);}}
【每日寄语】 人世间不可预料的事情太多了,但是不管怎样,社会还会照样运行。一个人不管有多大的成就,在世界万物中都是非常渺小的,所以要珍惜每一分每一秒。
