找出该链表的环的入口结点。
链表中环的入口结点
http://www.nowcoder.com/questionTerminal/253d2c59ec3e4bc68da16833f79a38e4
import java.util.ArrayList;
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
考察知识点:闭环,哈希法,双指针法
思路:1、用list存放节点,第一个重复的即为所求。
2、快慢指针,先找第一个在环中相遇的点,然后让快慢指针步长都为1,开始走,再次相遇的点即为所求。
*/
public class Solution {
//哈希法 public ListNode EntryNodeOfLoop(ListNode pHead){ if(pHead==null || pHead.next==null) return null; ArrayList<ListNode> list=new ArrayList<>(); ListNode temp=pHead; while(!list.contains(temp)){ list.add(temp); temp=temp.next; } return temp; } //双指针法 public ListNode EntryNodeOfLoop(ListNode pHead){ if(pHead==null || pHead.next==null) return null; ListNode fast=pHead; ListNode slow=pHead; while(fast!=null && fast.next!=null){ fast=fast.next.next; slow=slow.next; if(fast==slow){ fast=pHead; while(fast!=slow){ fast=fast.next; slow=slow.next; } return slow; } } return null; }
}