2.2 Implement an algorithm to find the kth to last element of a singly linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* nthToLast(ListNode *head, int k) {
ListNode *p1 = head;
ListNode *p2 = head;
for (int i = 0; i < k-1; i++) {
if (p2 == NULL) {
return NULL;
}
p2 = p2->next;
}
if (p2 == NULL) {
return NULL;
}
while (p2->next) {
p1 = p1->next;
p2 = p2->next;
}
return p1;
}