Given a single linked list, give only the pointer h:
1, how to determine whether there is a ring?
2, how to know the length of the ring?
3, how to find out where the ring connection point?
4. What is the length of the linked list?
Solution:
1, for the problem 1, using a catch-up method, set two pointers slow, fast, starting from the beginning of the hands, each step forward 1 steps, 2 steps. If there is a ring, the two meet; fast encounters a null exit if no ring exists.
2, for the problem 2, recorded the problem 1 of the collision point P,slow, fast from the point of the start, the number of collisions traversed by the length of the ring S.
3. Question 3: There is a theorem: the distance from the collision point P to the connection point = the distance from the head pointer to the connection point, so, starting from the collision point and the head pointer, the point of encounter is the connection point.
4, the problem 3 has been found in the length of the connection point distance head pointer, plus the length of the ring found in Problem 2, the sum of which is the length of a single linked list with a ring.
Procedure to determine if a loop exists:
BOOL Isexitsloop (slist *head) { slist *slow = head, *fast = head; while (Fast && fast->next) { slow = slow->next; Fast = fast->next->next; if (slow = = fast) break; } Return! (fast = = NULL | | fast->next = = NULL); }
a program that looks for a ring connection point (entry point):
slist* Findloopport (slist *head) { slist *slow = head, *fast = head; while (Fast && fast->next) { slow = slow->next; Fast = fast->next->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;
Single-linked list how to determine if there is a ring