如何判斷一個單鏈表是否有環(huán)?有環(huán)的話返回進入環(huán)的第一個節(jié)點的值,無環(huán)的話返回-1。如果鏈表的長度為N,請做到時間復(fù)雜度O(N),額外空間復(fù)雜度O(1)。
給定一個單鏈表的頭結(jié)點head(注意另一個參數(shù)adjust為加密后的數(shù)據(jù)調(diào)整參數(shù),方便數(shù)據(jù)設(shè)置,與本題求解無關(guān)),請返回所求值。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};*/
class ChkLoop {
public:
int chkLoop(ListNode* head, int adjust) {
// write code here
if(!head){return -1;}
ListNode *p1 = head, *p2 = head;
while(p2){
if(p2->next){
p2 = p2->next->next;
}else{
return -1;
}
p1 = p1->next;
if(p2 == p1){
break;
}
}
if(NULL == p2){
return -1;
}
p2 = head;
while(p1 != p2){
p1 = p1->next;
p2 = p2->next;
}
return p1->val;
}
};