標籤:count tno nod data make 實現 code 節點 namespace
/* * 尋找鏈表中環的入口節點.cpp * * Created on: 2018年4月10日 * Author: soyo */#include<iostream>using namespace std;struct Node{ int num; Node * next;};Node * creat(){ Node *head; Node *p; head=new Node; p=head; p->num=10; p->next=NULL; return head;}Node * insert(Node*head,int data){ Node *p1,*p; p1=new Node; p1->num=data; p1->next=NULL; p=head; while(p->next!=NULL) { p=p->next; } p->next=p1; return head;}Node * makeListCircle(Node *head,int n) //n代錶鏈表第幾個節點處設定為環的入口節點{ Node *p=head; Node *p2; //環的入口節點 int count=1; while(p->next!=NULL) { p=p->next; count++; if(count==n) { p2=p; } } p->next=p2; return head;}void printl(Node *head){ Node *p=head; while(p!=NULL) { cout<<"資料為:"<<p->num; p=p->next; } cout<<endl;}void printl_circle(Node *head){ Node *p=head; int count=0; while(p!=NULL) { if(count==10) break; //控制列印的總個數(不然無限迴圈) cout<<"資料為:"<<p->num; p=p->next; count++; } cout<<endl;}Node* meetNode(Node*head) //找到環中的節點{ if(head==NULL) return NULL; Node *pslow; pslow=head->next; Node *pfast; pfast=pslow->next; while(pfast!=NULL&&pslow!=NULL) { if(pfast==pslow) return pfast; pfast=pfast->next; pslow=pslow->next; if(pfast!=NULL) pfast=pfast->next; } return NULL;}Node * ringEntrance(Node * head) //找到環的入口{ Node*meetN=meetNode(head); int count=1; Node *p=meetN; Node *p2; while(p->next!=meetN)//確定環中節點的數目 { p=p->next; count++; } p=head; for(int i=0;i<count;i++) { p=p->next; } p2=head; while(p!=p2) { p=p->next; p2=p2->next; } return p2;}int main(){ Node *head=creat(); // cout<<head->num<<endl; int i,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); //環的入口節點 cout<<"環的入口節點的值為:"<<p->num<<endl;}
結果:
1 2 3 4 5資料為:10資料為:1資料為:2資料為:3資料為:4資料為:5資料為:10資料為:1資料為:2資料為:3資料為:4資料為:5資料為:4資料為:5資料為:4資料為:5環的入口節點的值為:4
C++實現尋找鏈表中環的入口節點