带环单链表的问题
因为上一篇文章对这个问题讲解的很详细,这里只给个代码展示:(找出带环单链表的环的第一个节点)
#include<iostream>using namespace std;int length;struct Node{int value;Node* next;};Node* meetCicleNode=NULL; //快节点和慢节点的相遇节点Node* firstCileNode=NULL; //环的第一个节点void createList(Node* &head) //创建一个带环的链表{int i;Node* current=head;Node* target_Node=NULL;for(i=0;i<length;i++){Node* temp=(Node*)malloc(sizeof(Node));temp->value=i;temp->next=NULL;current->next=temp;if(i==5)target_Node=temp;//指定这个节点为环的第一个节点current=temp;}current->next=target_Node; //链表末端指向中间的一个节点,这样就创建了一个带环单链表}bool isCicle(Node* head){Node* fast=head;Node* slow=head;do{if(fast&&slow){fast=fast->next->next;slow=slow->next;}else{cout<<"不是带环链表"<<endl;return false;}}while(fast!=slow);meetCicleNode=slow;return true;}void findFirstCicleNode(Node* head){if(isCicle(head)){Node* first=head;while(first!=meetCicleNode){meetCicleNode=meetCicleNode->next;first=first->next;}firstCileNode=first;}}void main(){length=10;Node* head=(Node*)malloc(sizeof(Node));head->value=0;createList(head);findFirstCicleNode(head);cout<<firstCileNode->value<<endl;}