- 判断链表是否带环?若带环求环的长度?若带环求环的入口点?
struct ListNode
{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL) { }
};
ListNode * IsHaveLoop(ListNode *phead)
{
assert(phead);
ListNode *pfast = phead;
ListNode *pslow = phead;
while(pfast && pfast->next)
{
pfast = pfast->next->next;
pslow= pslow->next;
if(pfast == pslow)
return pfast;
}
return NULL;
}
int LoopLen(ListNode *phead)
{
assert(phead);
ListNode*meetNode = IsHaveLoop(phead);
if(meetNode == NULL) //无环,长度为0
return 0;
ListNode *pcur = meetNode->next;
int len = 1;
while(pcur != meetNode)
{
len++;
pcur = pcur->next;
}
return len;
}
//求环的入度点(一个指针从头开始走,一个指针从相遇点开始走,最终两个指针会在度点相遇)
//推理: 假设链表从头到环入度的长度是L,环的长度是R,环的入度到快慢指针相遇的节点的长度是X。快指针走的速度是慢指针的二倍。
////慢指针走的长度是L+X,快指针走的长度是L+X+nR, ==》 2*(L+X) = L+X+nR. ==> L = nR -X
//// 当n = 1, 表示链表从头到环入度的距离等于从相遇点到环入度的距离。
ListNode * EntryNode(ListNode *phead)
{
assert(phead);
ListNode *pmeet = IsHaveLoop(phead);
if(pmeet == NULL) //无环
return NULL;
ListNode *p1 = phead;
ListNode *p2 = pmeet;
while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
if(p1 == p2)
return p1;
}
return phead; //一个节点单独成为环。
}
class A
{
public:
static A* GetHandler()
{
A*handler = new A();
return handler;
}
static void DeleteHandler(A* handler)
{
delete handler;
}
private:
A(){ cout << "构造函数被执行了"<<endl; }
~A(){ cout << "析构函数被执行了"<<endl; }
};
class A
{
protected:
A(){ cout << "A的构造函数被执行了"<<endl;}
~A() { cout << "A的析构函数被执行了"<< endl; }
public:
static A*GetHandler()
{
A* handler = new A();
return handler;
}
static void DeleteHandler(A *handler)
{
delete handler;
}
};
class A
{
public:
A() { cout << "A的构造函数被执行了" << endl; }
~A() { cout << "A的析构函数被执行了" << endl;}
private:
void * operator new(size_t size){ }
void operator delete(void *p) { }
};