Topic:
A linked list contains a ring, how to find the entry node of the ring? For example 1->2->3->4->5->6-> (3); In the linked list, the entrance of the ring and where is the node 3.
Analytical:
- First find the link in the list of rings: Define 2 pointers, a fast pointer to walk 2 step at a time, a slow pointer to walk 1 steps, if 2 pointers can meet, proving that there is a ring.
- Count the length of the ring in the list: Starting with the meeting pointer, fixing 1 pointers, another pointer walking from the meeting pointer, and when 2 pointers meet again, that is 1 laps to get the length of the ring Len.
- 2 pointers to the beginning of the list, 1 pointers to the Len step, and the other pointer to the previous one, and when the 2 pointers meet, the entrance to the ring.
#include <iostream>Using namespace Std;class Node { Public: int val; Node*Next node (int v, node*N= NULL): Val (v), Next (n) {};}; int Getcirclenodenums (Node*Phead) {if(Phead== NULL)return 0;//A fast and slow, meet, then find the ringNode*Pslow=Phead; Node*Pfast=Pslow -Next while(Pfast!= NULL &&Pslow!= NULL) {if(Pfast==Pslow) break; Pslow=Pslow -Nextif(Pfast -Next) {Pfast=Pfast -Next -Next }Else{break; } }//Fixed a pointer, a pointer walked, met again when it was a lap, to get the ring lengthint counts= 0;//If p1, p2 has a null, there is no ring, return 0Node*P1=Pfast,*P2=Pslow;if(P1==P2&&P1!= NULL) {P1=P1 -Next Counts++; while(P1!=P2) {P1=P1 -Next Counts++; } }returnCounts;} Node*Findcircleentrance (Node*Phead) {if(Phead== NULL)return NULL; int Circle_len=Getcirclenodenums (Phead);if(Circle_len== 0)return NULL;//No ringNode*P1=Phead,*P2=Phead;//P1 the length of a ring first . while(Circle_len) {P1=P1 -Next Circle_len--; }///P1, p2 Walk together, the meeting is the entrance of the ring while(P1!=P2) {P1=P1 -Next P2=P2 -Next }returnP1;} int main () {//1->2->3->4->5->6-> (3)Node*PList= NULL; Node*PNode1= NewNode (1,NULL); Node*PNode2= NewNode (2,NULL); Node*PNode3= NewNode (3,NULL); Node*PNode4= NewNode (4,NULL); Node*PNode5= NewNode (5,NULL); Node*PNode6= NewNode (6,NULL); PNode1 -Next=PNode2; PNode2 -Next=PNode3; PNode3 -Next=PNode4; PNode4 -Next=PNODE5; PNode5 -Next=PNode6; PNode6 -Next=PNode3; PList=PNode1; cout<< "The length of the ring:"<<Getcirclenodenums (PList)<<Endl Node*Entrancenode=Findcircleentrance (pList);if(Entrancenode) cout<< "The value of the portal node of the ring:"<<Entrancenode -Val<<Endl;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
56-The entry node of the ring in the linked list