1. 程式人生 > >C++實現查找鏈表中環的入口節點

C++實現查找鏈表中環的入口節點

n) head break 控制 style fast ast 無限循環 AC

/*
 * 尋找鏈表中環的入口節點.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++實現查找鏈表中環的入口節點