, if the single-linked list has a ring, then when traversing, after passing 6, will be back to 3, then we can use two pointers during the traversal to see whether two pointers are equal.
Method One: Use P, q Two pointers, p always go forward, but Q every time to start from the beginning, for each node, see p Walk step number is the same as Q. , when p from 6 to 3 o'clock, with 6 steps, at this time if Q from head, then only two steps to 3, thus varying the number of steps, there are contradictions, the existence of the ring
Method Two: Use P, q two pointers, p each step forward, Q each forward two steps, if at some point p = = Q, there is a ring.
#include <stdio.h>#include<stdlib.h>#defineLEN 8typedefstructnode*node_t;structnode{CharVal; structNode *Next; }; //Method 1intHas_loop (structNode *head);//Method 2intHas_loop2 (node_t head);intMain () {node_t* arr = (node_t*)malloc(sizeof(structnode) *LEN); arr[0] = (node_t)malloc(sizeof(structnode)); inti; for(i =1; i < LEN; i++) {Arr[i]= (node_t)malloc(sizeof(structnode)); Arr[i-1]->next =Arr[i]; } Arr[len-1]->next =NULL; //You can add a loop here to test//arr[6]->next = arr[0]; if(Has_loop (arr[0]) printf ("Method1:has loop.\n"); Elseprintf ("Method1:has No loop.\n"); if(Has_loop2 (arr[0]) printf ("Method2:has loop.\n"); Elseprintf ("Method2:has No loop.\n"); return 0;}//If the pointer is equal, but they don't have the same steps and then has a loopintHas_loop (node_t head) {node_t Cur1=Head; intPOS1 =0; while(cur1) {node_t cur2=Head; intPos2 =0; POS1++; while(CUR2) {Pos2++; if(CUR2 = =cur1) { if(POS1 = =Pos2) Break; Else return 1; } CUR2= cur2->Next; } cur1= cur1->Next; } return 0; } //using Step1 and Step2 here//if exists a loop, then the pointer which use Step2 'll catch up with the pointer which uses STEP1intHas_loop2 (node_t head) {node_t P=Head; node_t Q=Head; while(P! = NULL && Q! =NULL) { /*p = p->next; if (q->next! = NULL) Q = q->next->next; if (p = = q) return 1; */ //correct it on 17/11/2012p = p->Next; Q= q->Next; if(Q! =NULL) Q= q->Next; if(P! = NULL && p = =q)return 1; } return 0;}
Translated from http://www.cnblogs.com/shuaiwhu/archive/2012/05/03/2480509.html
Two methods of judging whether a single linked list has a ring (turn)