题目描述
一个链表中包含环,请找出该链表的环的入口结点。
使用hash
import java.util.*;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
HashSet<ListNode> set = new HashSet();
while(pHead != null){
if(set.contains(pHead)){
return pHead;
}else{
set.add(pHead);
pHead = pHead.next;
}
}
return null;
}
}
链表指针的方法:
首先,使用链表判断是否有环的方法(快慢指针,单双),得到环中的一个节点;
然后,得到环中节点的总个数count;
最后,使用链表倒数第k个节点的方法让快指针先走 count个节点,然后两指针汇合之处就是环的入口!
import java.util.*;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null)
return pHead;
ListNode fast = pHead,slow = pHead;
ListNode tmp = null;
while(fast != null){
slow = slow.next;
if(slow == null)
return null;
fast = fast.next.next;
if(fast == null)
return null;
if(fast == slow){
tmp = fast;
break;
}
}
ListNode p = tmp.next;
int count = 1;
while(p != tmp){
p = p.next;
count++;
}
fast = pHead;
slow = pHead;
for(int i=0;i<count;i++){
fast = fast.next;
}
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return fast;
}
}
在判断是否有环的时候注意:要时刻判断当前的节点是否为null。
slow = slow.next;
if(slow == null) return null;
fast = fast.next.next;
if(fast == null) return null;