Title Description
Input a linked list, the linked list output reciprocal k-th node.
Problem-solving ideas
Speed method using the pointer, so go fast pointer k steps, then let go slow start pointer, when the pointer reaches the quick list tail pointer just slow to reach the penultimate k nodes.
C ++ code to achieve:
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
if(pListHead==NULL){ return NULL; } ListNode *p1,*p2; p1=pListHead; int count=0; int pos=k; while(POS> 0 && P1 =! NULL) { P1 = P1-> Next; POS - ; COUNT ++ ; } // if the chain length is less than K, inputs are not valid, return NULL IF (COUNT =! K) { return NULL; } P2 = pListHead; the while (P1 =! NULL) { P1 = P1-> Next; P2 = P2-> Next; } return P2; } };