Linked List structure:
TypedefStructListnode {IntVal;StructListnode *Next;} listnode;
1. Determine whether a single-chain table has loops
This problem uses the pursuit method to define two pointers, one taking two steps at a time and one taking one step at a time. If the two pointers meet each other, it indicates that there is a ring.
Int Is_cycle (linklist * List ){ If (List = NULL | list-> next = NULL) Return -1 ; Linklist * Fast = List; linklist * Slow = List; While (Fast! = NULL & fast-> next! = Null) {fast = Fast-> next-> Next; slow = Slow-> Next; If (Fast = slow) Return 0 ;} Return -1 ;}
2. Determine the starting position of a single-link table loop with a ring
There is a theorem. In the first question, the distance between the two pointers and the starting position of the ring is equal to the distance from the head of the linked list to the starting position of the ring. In this way, it is not difficult to find the node at the beginning of the ring.
Linklist * begin_cycle (linklist * Head ){ If (Head = NULL | head-> next = NULL) Return NULL; linklist * Fast = Head; linklist * Slow = Head; While (Fast! = NULL & fast-> next! = Null) {fast = Fast-> next->Next; slow = Slow-> Next; If (Slow = fast) Break ;} If (Fast = NULL | fast-> next = NULL) Return NULL; // determines whether a ring exists. If no ring exists, null is returned. (If it is clear that it is a ring, this is not acceptable) Slow = Head; While (Slow! = Fast) {slow = Slow-> Next; fast = Fast->Next ;} Return Fast ;}
Apart from the above two problems, the other one is to find the length of the ring and the length of the linked list. These two problems should be very simple. Starting from the encounter point, one pointer loops and the other waits, the path we walk through when we meet again is a whole ring. With the length of the ring and the starting point of the ring, it is not difficult to find the length of the linked list. (Plus the length from the header to the start point)
Problems related to making a single-chain table Ring