1, linked list definition
typedef struct LISTELEMENT_T_ { void *data; struct Listelement_t_ *next;} listelement_t;typedef struct list_t_{ int size; int capacity; listelement_t *head; listelement_t *tail;} list_t;
2, to determine whether the link list has a ring, and return to the Link list entry node
(1) method one: Based on the distance relationship between the node, the head node and the entrance nodes
The goal is to look at the relationship between the distance between the head node and the meeting point and the distance between the node and the entry node.
Assuming that the link header node to the entry point distance is S1, the entry node once to meet the distance of the node is S2, the meeting node once traversed to the inlet node distance of S3, the ring length is l, then L = S2 + S3:
When the speed of the first encounter, the fast pointer to traverse the total number of nodes is Fn, the total number of slow pointer traversal is Sn, at this time the slow pointer has not completed a loop of one traversal, and the fast pointer completes the loop at least one traversal, the slow pointer distance is: Sn = S1 + S2, fast pointer distance is: Fn = S1 + (n >= 1),
List the equations for:
L = S2 + S3
Fn = 2*SN
Fn = S1 + S2 + n*l
Sn = S1 + S2
= = "Look at the relationship between S1 and S3.
S1 + S2 + n*l = (S1 + S2)
i.e.: S1 + S2 + N (S2 + S3) = (S1 + S2)
==> S1 = n * (S2 + S3)-S2
==> S1 = n * (S2 + S3)-(S2 + S3) + S3
==> S1 = (n-1) * (S2 + S3) + S3
==> S1 = (n-1) * L + S3
Because of the n>=1, so when the head node and meet nodes at the same time, will certainly meet at the entrance node, and the first encounter node must be the entry node:
listelement_t *getenternode (list_t *list) { if (List = = NULL | | list->head = = NULL) return null; listelement_t *pfast = list->head; listelement_t *pslow = list->head; while (pfast->next! = NULL && Pfast->next->next! = null{ pfast = pfas->next->next; Pslow = pslow->next; if (pfast = = Pslow) break ; } Can't use Pfast! =pslow, because if there is only one node, this is equal if (Pfast->next = = NULL | | pfast->next->next = = NULL) return NULL; Pslow = list->head; while (pslow! = pfast) { Pslow = pslow->next; Pfast = pfast->next; } return pslow;}
(2) Method Two: In the meeting node, according to the way of the intersection list to solve
List----Determine if the list has loops and return to the Ring entry node