給一個鏈表,若其中包含環,請找出該鏈表的環的入口結點,不然,輸出null。java
public ListNode entryNodeOfLoop(ListNode pHead) {
if (pHead == null) {
return null;
}
//先找到環中的某個節點
ListNode meetingNode = meetingNode(pHead);
int count = 1;
ListNode node = meetingNode;
//計算環中的節點個數
while (node.next != meetingNode) {
count++;
node = nodex.next;
}
ListNode node1 = pHead, node2 = pHead;
//先讓一個節點走節點個數步
for (int i = 0; i < count; i++) {
node1 = node1.next;
}
//開始找到環的入口節點
while (node1 != node2) {
node1 = node1.next;
node2 = node2.next;
}
return node2;
}
//返回環中的節點
public ListNode meetingNode(ListNode pHead) {
//分別聲明快指針和慢指針
ListNode slow = pHead, fast = pHead.next;
while (fast != null) {
if (fast == slow) {
return fast;
}
slow = slow.next;
fast = fast.next;
//防止空指針異常
if (fast != null) {
fast = fast.next;
}
}
return null;
}
複製代碼