There is a single-chain table, where there may be a ring, that is, the next of a node points to the previous node in the linked list, so that a ring is formed at the end of the linked list.
Problem:
1. How to determine whether a linked list is such a linked list?
2. If the linked list contains an existing ring, how can we find the entry point of the ring?
Answer:
1. Determine whether the linked list has a ring. The method is as follows:
Set two pointers (fast and slow). The initial values all point to the header. Slow moves one step forward each time, and fast moves two steps forward each time. If the linked list has a ring, fast must first enter the ring, when slow enters the ring, the two pointers must meet each other. (Of course, if the first line to the end of fast is null, it is a non-ring linked list)ProgramAs follows:
Bool isexitsloop (slist * head) {slist * slow = head, * fast = head; while (Fast & fast-> next) {slow = slow-> next; fast = fast-> next; If (slow = fast) break;} return! (Fast = NULL | fast-> next = NULL );}
2. Find the entry point of the ring
When fast encounters slow, slow certainly does not traverse the linked list, and fast already loops n circles (1 <= N) in the ring ). Assume that slow takes the s step, then fast takes 2 s step (the number of fast steps is equal to the number of S plus N turns on the ring), set the ring length to R, then:
2 S = S + nR
S = nR
Set the length of the entire linked list to L. The distance between the entrance ring and the encounter point is X, and the distance from the start point to the entrance point is.
A + x = nR
A + x = (n-1) R + r = (n-1) R + L-
A = (n-1) R + (L-a-x)
(L-a-x) is the distance from the encounter point to the ring entry point. From this point, we can see that from the chain table header to the ring entry point is equal to (n-1) the cycle inner ring + the encounter point to the ring entry point, so we set a pointer from the head of the linked list and from the encounter point. Each time we take a step, the two pointers must meet each other and the first point of the encounter is the ring entry point. The program is described as follows:
Slist * findloopport (slist * head) {slist * slow = head, * fast = head; while (Fast & fast-> next) {slow = slow-> next; fast = fast-> next; If (slow = fast) break;} If (fast = NULL | fast-> next = NULL) return NULL; slow = head; while (slow! = Fast) {slow = slow-> next; fast = fast-> next;} return slow ;}