Given a circular linked list, implement an algorithm which returns node at the begin-
ning of the loop
DEFINITION
Circular linked list: A (corrupt) linked list in which a node’s next pointer points to an
earlier node, so as to make a loop in the linked list
EXAMPLE
input: A -> B -> C -> D -> E -> C [the same C as earlier]
output: C
可以用龟兔原则解这个题。即快指针每次走两格,慢指针每次走一格,那么在慢指针遍历一次之前会相遇。相遇以后,快指针回原地点,每次一格,慢指针每次一格,在此相遇即为环点。
具体证明有http://www.1point3acres.com/bbs/viewthread.php?tid=18162
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(){this->next = 0;}
Node(int a):data(a),next(0){}
};
class LinkList{
public:
Node* head;
Node* tail;
LinkList(){
head = new Node(-1);
tail = head;
}
LinkList(int ar[],int len){
head = new Node(-1);
tail = head;
for(int i = 0; i<len; i++){
tail->next = new Node(ar[i]);
tail = tail->next;
}
}
void insertion(int);
Node* del(int i);
void print()const{
Node* p = head->next;
while(p)
{
cout<<p->data<<" ";
p = p->next;
}
}
};
void LinkList::insertion(int k){
tail->next = new Node(k);
tail = tail->next;
}
Node* LinkList::del(int i){
Node* p = head->next;
Node* k = head;
while(p->data != i){
k = p;
p = p->next;
}
k->next = p->next;
delete(p);
return p->next;
}
int runn(LinkList l){
Node* slow_p = l.head->next;
Node* fast_p = l.head->next->next;
while(slow_p != fast_p){
slow_p = slow_p->next;
fast_p = fast_p->next->next;
}
fast_p = l.head;
while(slow_p != fast_p){
slow_p = slow_p->next;
fast_p = fast_p->next;
}
return slow_p->data;
}
int main(){
int ar[]={1,3,5,67,8,9,45,78,777,33,12,11,76,4,43,7};
LinkList ll(ar,16);
Node* p = ll.head;
for(int i = 1; i<=7; i++)
p = p->next;
ll.tail->next = p;
cout<<runn(ll)<<endl;
}