Find the reciprocal k element in a single linked list
Problem Solving Ideas:
In order to find out the list of the second-to-last K-element, the most likely way is to first traverse the single-linked list, the entire single-linked list of the length of N, and then the reciprocal K, converted to a positive number n-k, and then go through one time to get the results. However, this method requires two traversal of the linked list, the first traversal is used to solve the single-linked list length, and the second traversal is used to find the positive number of the n-k element.
If you start with an element in the list from the beginning to the end and traverse the K element just to the tail of the chain, then the element is the penultimate element to find. The design is as follows: In turn, each node element of the linked list is tested such that the k element is traversed to see if it reaches the end of the chain until the last K element is found. This method will iterate over the same batch of elements repeatedly, for most elements of the list, to traverse the k elements, if the chain table length is n, then the algorithm time complexity of O (kn), the efficiency is too low.
There is another more efficient way. During the lookup process, set two pointers so that one pointer moves k-1 than the other, and the two pointers move forward at the same time. Loop until the first pointer is null, the position that the other pointer refers to is the position you are looking for
The procedure is as follows:
PublicNodeFindelem(Node Head,intK) {if(k<1|| Head = =NULL) {return NULL; } Node p1 = head; Node P2 = head; for(inti =0; I < K-1; i++) {//move forward k-1 step if(P1.next! =NULL) {P1 = P1.next; }Else{return NULL; } } while(P1! =NULL) {P1 = P1.next; P2 = p2.next; }returnP2; }
GitHub Source Address
Https://github.com/GeniusVJR/Algorithm-and-Data-Structure/tree/master/the penultimate element of a single linked list
[algorithm] finds the reciprocal K element in a single linked list