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

來源:互聯網
上載者:User

標籤: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++實現尋找鏈表中環的入口節點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.