https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
Topic a:
Method one: traverse the entire list to find the length of the list and find a length to traverse the list - k + 1 is for the return value
The class Solution {
Public:
Int kthToLast (ListNode * head, int k) {
Int length=0;
ListNode * phead=head;
//the length of the traverse the list
While (phead - & gt; Next!=NULL) {
length++;
Phead=phead - & gt; next;
}
Phead=head;
For (int I=0; I & lt;=length - k; I++)
{
Phead=phead - & gt; next;
}
Return phead - & gt; Val.
}
};
Method 2: how Pointers: double pointer
Initialize the two Pointers p and q, let it points to the head node, p mobile k times first, so that the distance between p and q, k and p and q move together, until the p point to null
Code:
ListNode * phead=head;
ListNode * qhead=head;
//the length of the traverse the list
While (k -) {
Phead=phead - & gt; next;
}
While (phead!=NULL) {
Phead=phead - & gt; next;
Qhead=qhead - & gt; next;
}
Return qhead - & gt; Val.