Give a list of the head pointers, ask to find the bottom k node, and output the value of this node
Example:
First look at an example, the list is: 1 2 3 4 5 6, the bottom 2nd node is 5, the penultimate node is 6, and so on. The list here has a head node, which means that head->next is pointing to the first node. The data structure of the linked list is as follows:
1 // ListNode 2 struct Lnode {3 int key; 4 struct Lnode *Next; 5 }
Analysis:
We now only know the list of the head pointer, and the length of the list is unknown, then what to do?
One way that might come out of our mind first is to traverse the list first, to determine the length of the linked list, and then the countdown k node, which is the (length-k + 1) node. Of course this method can solve the problem, but it takes two times to traverse the list, if you go to the interview, you answer the interviewer, then this is obviously not the algorithm that the interviewer wants. So is there a better way to traverse the problem at once?
The answer is yes.
1. First, you can point to the head node with P1,P2 two pointers:
2. Then let P2 move the K (k=2) nodes forward first:
3. Then let P1,P2 move forward simultaneously, when P2 is empty, that is, P2 points to the next node (NULL) of the last node, the node that P1 points to is the penultimate K node:
Code:
1 //find the last k-th node of list2 intFindKey (Lnode *head,intk) {3Lnode *P1 =head;4Lnode *P2 =head;5 6 //p2 move on K nodes7 while(k-->0)8P2 = p2->Next;9 Ten //Then P1 and P2 both move on until P2 = NULL One while(p2) { AP1 = p1->Next; -P2 = p2->Next; - } the - returnP1->key; -}
[JOBDU] Topic 1517: List of the last K nodes in a list