上次看到的题目仅是判断是否有环,如果要求出环的起点位置又该如何呢?
这里看到关于快慢指针的证明,感觉有必要记下来下。
假设链表头到环头距离k,环长度n,指针相遇位置距离环头为x,慢指针直到相遇时移动距离为m
那么有m=k+x+pn,2m-m=qn;
那么有qn=k+x+pn,即k+x=(q-p)n;
可以发现从表头到相遇位置的距离是环长的整数倍。
那么,将slow或者fast任意一个指针从相遇位置直接移动到表头。
然后while(slow!=fast)slow++,fast++(这里fast也只一次一步)
那么最后slow=fast时,一定是环头位置。
node * f(node* head) { node* slow =head,fast=head; while(slow!=head)//就不考虑环不存在的情况了 { slow=slow->next; fast=fast->next->next; } fast=head; while(fast!=slow) { slow=slow->next; fast=fast->next; } return fast; }
不过这种方法比较tricky,学c++的应该想到这样的方法、
map<node*,bool>看到这个容器自然就该知道接下来怎么写了
node * f(node* head) { map<node*,bool> hash; while(!map[head]) { map[head]=true; head++; } return head; }