题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
题目链接:
分析:
空间换时间。
set记录之前出现过的节点。
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ import java.util.HashSet; public class Solution { private HashSet<ListNode> set = new HashSet<>(); public ListNode EntryNodeOfLoop(ListNode pHead) { ListNode cur = pHead; while(cur != null){ if(set.contains(cur)){ return cur; } set.add(cur); cur = cur.next; } return null; } }
方法二:
快慢节点。详见:https://www.nowcoder.com/questionTerminal/253d2c59ec3e4bc68da16833f79a38e4
/* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } */ public class Solution { public ListNode EntryNodeOfLoop(ListNode pHead) { if(pHead.next == null || pHead.next == null || pHead.next.next == null){ return null; } //一开始需要先走一次? ListNode fast = pHead.next.next; ListNode slow = pHead.next; while(fast != slow){ //快的走两步,慢的走一步 if(fast.next != null && fast.next.next != null){ fast = fast.next.next; slow = slow.next; }else{ return null; } } fast = pHead; //x = (n - 2 * m )*c - a= (n - 2 *m -1 )*c + c - a //相遇节点即入口 while(fast != slow){ fast = fast.next; slow = slow.next; } return slow; } }