CircularLinkedListII题目描述:给定一个链表,返回链表开始入环的第一个节点。如果列表是非循环的,则返回null。为了表示给定列表中的循环,我们使用整数pos来表示列表中尾部连接的位置(索引从0开始)。如果pos为-1,则列表中没有循环。请注意,pos仅用于标识环,不会作为参数传递给函数。说明:不允许修改给定的链表。高级:你能用O(1)空间解决这个问题吗?例子见LeetCode官网。来源:LeetCode链接:https://leetcode-cn.com/probl...版权归LeetCode所有。商业转载请联系官方授权,非商业转载请注明出处。方案一:哈希表HashSet判断节点是否重复。方案二:双指针法使用快节点和慢节点。如果存在循环,则两个节点必须相遇。importjava.util.HashSet;importjava.util.Set;publicclassLeetCode_142{/***hash**@paramhead*@return*/publicstaticListNodedetectCycle(ListNodehead){if(head==null){返回空值;}Setnodes=newHashSet<>();节点.添加(头);while(head.next!=null){//如果哈希表中已经出现下一个节点,则表示环已经完成,下一个节点一定是入口点,直接返回if(nodes.contains(head.下一个)){返回head.next;}nodes.add(head.next);head=head.next;}返回空值;}/***双指针方法**@paramhead*@return*/publicstaticListNodedetectCycle2(ListNodehead){if(head==null){returnnull;}ListNodeslow=head,fast=head;while(fast!=null){slow=slow.next;if(fast.next!=null){fast=fast.next.n分机;}else{返回空值;}if(fast==slow){ListNodeptr=head;while(ptr!=slow){ptr=ptr.next;慢=慢.next;}返回指针;}}返回空值;}publicstaticvoidmain(String[]args){ListNodehead=newListNode(3);head.next=newListNode(2);head.next.next=newListNode(0);head.next.下一个。next=new列表节点(-4);head.next.next.next.next=head.next;System.out.println(detectCycle(head)==null?-1:detectCycle(head).val);系统。out.println(detectCycle2(head)==null?-1:detectCycle2(head).val);}}【每日一帖】世界上有太多不可预知的事情,但不管怎样,社会还是会运行一个人的成就再大,在世界上都是非常渺小的,所以我们要珍惜每一分每一秒每一秒。