题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解题思路
努力回想终于想起了书上的做法,然而code中出现了段错误,主要是下面一段,仔细检查才发现。
if(p2->next) p2 = p2->next;
改为
if(p2) p2 = p2->next;
Code
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
int GetCycleLength(ListNode* pHead) {
if(pHead == nullptr) return -1;
ListNode *p1 = pHead, *p2 = pHead->next;
if(p2) p2 = p2->next;
int hasCycle = 0, countP1 = 0, countP2 = 0;
while(p1 && p2) {
if(p1 && p1 == p2) {
if(!hasCycle) {
hasCycle = 1;
} else {
return countP2-countP1;
}
}
if(hasCycle) {
countP1++, countP2 += 2;
}
p1 = p1->next;
p2 = p2->next;
if(p2) p2 = p2->next;
}
return -1;
}
ListNode* EntryNodeOfLoop(ListNode* pHead){
if(!pHead) return nullptr;
ListNode* pNode = pHead;
int cycleLength = GetCycleLength(pNode);
if(cycleLength == -1) {
return nullptr;
}
ListNode *p1 = pHead, *p2 = pHead;
for(int i = 0; i<cycleLength; i++) {
p2 = p2->next;
}
while(p1 != p2) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
};
- java
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int getCycleLength(ListNode pHead) {
ListNode p1 = pHead, p2 = pHead;
p2 = p2!=null && p2.next!=null ? p2.next.next : null;
while(p1!=null && p2!=null && p1 != p2) {
p1 = p1.next;
p2 = p2!=null && p2.next!=null ? p2.next.next : null;
}
if(p1 == null || p2 == null) return -1;
int length = 0;
do {
length++;
p1 = p1.next;
p2 = p2!=null && p2.next!=null ? p2.next.next : null;
} while(p1 != p2);
return length;
}
public ListNode EntryNodeOfLoop(ListNode pHead)
{
int cycleLength = getCycleLength(pHead);
if(cycleLength == -1) return null;
ListNode p1 = pHead, p2 = pHead;
for(int i = 0; i<cycleLength; i++) {
p2 = p2.next;
}
while(p1 != p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}