/** Look for the entry node of the link in the list. cpp * * Created on:2018 April 10 * Author:soyo*/#include<iostream>using namespacestd;structnode{intnum; Node*next;}; Node*creat () {Node*Head; Node*p; Head=NewNode; P=Head; P->num=Ten; P->next=NULL; returnHead;} Node* Insert (Node*head,intdata) {Node*p1,*p; P1=NewNode; P1->num=data; P1->next=NULL; P=Head; while(p->next!=NULL) {P=p->Next; } P->next=P1; returnHead;} Node* Makelistcircle (Node *head,intN//N Represents the entry node set as a ring at the first node of the list{Node*p=Head; Node*P2;//The entry node of the ring intCount=1; while(p->next!=NULL) {P=p->Next; Count++; if(count==N) {p2=p; }} P->next=P2; returnhead;}voidPrintl (Node *head) {Node*p=Head; while(p!=NULL) {cout<<"The data are:"<<p->num; P=p->Next; } cout<<Endl;}voidPrintl_circle (Node *head) {Node*p=Head; intCount=0; while(p!=NULL) { if(count==Ten) Break;//control the total number of prints (otherwise infinite loops)cout<<"The data are:"<<p->num; P=p->Next; Count++; } cout<<Endl;} Node* Meetnode (Node*head)//find the nodes in the ring{ if(head==NULL)returnNULL; Node*Pslow; Pslow=head->Next; Node*Pfast; Pfast=pslow->Next; while(pfast!=null&&pslow!=NULL) { if(pfast==Pslow)returnPfast; Pfast=pfast->Next; Pslow=pslow->Next; if(pfast!=NULL) Pfast=pfast->Next; } returnNULL;} Node* Ringentrance (Node * head)//find the entrance to the ring{Node*meetn=Meetnode (head); intCount=1; Node*p=Meetn; Node*P2; while(P->NEXT!=MEETN)//determine the number of nodes in the ring{p=p->Next; Count++; } P=Head; for(intI=0; i<count;i++) {p=p->Next; } P2=Head; while(p!=p2) {P=p->Next; P2=p2->Next; } returnp2;}intMain () {Node*head=creat (); //cout< intI,data; for(i=0;i<5; i++) {cin>>data; Head=Insert (Head,data); } printl (head); Makelistcircle (Head,5); Printl_circle (head); Node*p; P=ringentrance (head);//The entry node of the ringcout<<"The value of the entry node for the ring is:"<<p->num<<Endl;}
Results:
1 2 3 4 5 data: 10 Data: 1 Data: 2 data: 3 data is: 4 data is: 5 data: 10 Data: 1 Data: 2 data: 3 Data : 4 data: 5 Data: 4 Data: 5 Data: 4 5 The value of the entry node for the ring is: 4
C + + implementation finds the entry node for a ring in a linked list