判斷鏈表有公共點
阿新 • • 發佈:2018-04-04
random == log ner nodes 結點 true logs rand
判斷兩個鏈表是否相匯,可以通過將第一個鏈表的尾部與第二個鏈表的頭部相連接,如果鏈表形成了環,則說明鏈表相匯了。
/* * 兩個鏈表是否公共結點 */ #include<iostream> #include<ctime> #include<cstdlib> #include<cstdio> using namespace std; typedef struct node* link; typedef struct node{ int value; link next; node(){ value=-1; next=NULL; } node(int v){ value=v; next=NULL; } }Node; void GenerateList(link& head1,link& head2){ int n=rand()%100+1; head1=new Node(); head2=new Node(); link p1=head1,p2=head2; for(int i=0;i<n;i++){ int x=rand()%100+1; p1->next=new Node(x); p1=p1->next; } int m=rand()%100+1; for(int i=0;i<m;i++){ int x=rand()%100+1; p2->next=new Node(x); p2=p2->next; } p1->next=p2; //if this statement is deleted, the two lists will have no common points; printf("the random common point's address:%d\n",p2); int k=rand()%100+1; for(int i=0;i<k;i++){ int x=rand()%100+1; p2->next=new Node(x); p2=p2->next; } head1->value=n+k+1; head2->value=m+k; } bool FindCircle(link head){ link p=head; while(p->next!=NULL){ p=p->next; if(p==head){ return true; } } return false; } int main(){ srand((unsigned)time(NULL)); link head1=NULL,head2=NULL; GenerateList(head1,head2); // connect tail of list1 to the head of list2 link p=head1; while(p->next!=NULL) p=p->next; p->next=head2; //judge whether there exists a circle if(FindCircle(head2)){ if(head1->value<head2->value){ int count=head2->value-head1->value; while(count--){ head2=head2->next; } }else{ int count=head1->value-head2->value; while(count--){ head1=head1->next; } } while(head1!=head2){ head1=head1->next; head2=head2->next; } printf("the common point's address:%d\n",head1); }else{ printf("No common nodes\n"); } return 0; }
判斷鏈表有公共點