链表中环的入口节点
描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
解题
单链表
public class ListNode {
int val;
ListNode next = null;
public ListNode(int val) {
this.val = val;
}
}
Solution
/**
* 拆分法
*/
public class Solution {
public ListNode EntryNodeOfloop(ListNode pHead){
if (pHead==null) return null;
while (pHead.next!=null){
ListNode temp = pHead.next;
if (pHead==temp){
return temp;
}else {
pHead.next=pHead;//拆分
pHead=temp;//遍历
}
}
return null;
}
}