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

/*
 * 尋找鏈表中環的入口節點.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;
}

結果:ios

1 2 3 4 5
數據爲:10數據爲:1數據爲:2數據爲:3數據爲:4數據爲:5
數據爲:10數據爲:1數據爲:2數據爲:3數據爲:4數據爲:5數據爲:4數據爲:5數據爲:4數據爲:5
環的入口節點的值爲:4
相關文章
相關標籤/搜索