//============================================================================ // Name : 100题之找出链表的第一个公共节点.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; class Node { public: int date; Node *next; Node(int date1=0):date(date1),next(NULL){} }; void create(Node **Head,int date) { Node *p=new Node(date); if(!(*Head)) { *Head=p; } else { p->next=(*Head); (*Head)=p; } } void print(Node *head) { while(head) { cout<<head->date<<" "; head=head->next; } cout<<endl; } int Length(Node*head) { int number=0; while(head) { number++; head=head->next; } return number; } Node *findFrist(Node*p1,Node *p2) { int length1=Length(p1); int length2=Length(p2); Node *temp1=(length1>length2?p1:p2); Node *temp2=(length1<length2?p1:p2); int path=(length1>length2?length1-length2:length2-length1); cout<<"path "<<path<<endl; for(int i=1;i<=path;i++) temp1=temp1->next; cout<<temp1->date<<endl; while(temp1&&temp2&&temp1!=temp2) { temp1=temp1->next; temp2=temp2->next; } if(!temp1&&!temp2) return NULL; if(temp1==temp2) return temp1; } int main() { Node *head=NULL; create(&head,1); create(&head,2); create(&head,3); create(&head,4); create(&head,5); print(head); Node *head1=NULL; create(&head1,10); create(&head1,20); head1->next->next=head; print(head1); Node *result=findFrist(head,head1); if(!result) cout<<"no"<<endl; else cout<<result->date<<endl; return 0; }